<?php
namespace Lia;
class Addon {
/**
* Fully qualified name for accessing this addon
*/
public string $fqn;
/**
* The short name of this addon
*/
public string $name;
/** Package */
public ?\Lia\Package $package;
public ?\Lia $lia;
/**
* Get an instance of the addon class from the Liaison object based on the default `fqn` of the called class, or throw if it isn't on the lia object.
*
* @param $lia \Lia instance
* @return instance of the called addon class
* @throws if the instance is not available on the passed-in liaison instance
*/
static public function from(\Lia $lia): static {
$class = static::class;
$ref = new \ReflectionClass($class);
$fqn = $ref->getDefaultProperties()['fqn'];
$addon = $lia->addon($fqn);
if ($addon instanceof $class)return $addon;
else throw new \Exception("Addon with class '".static::class."' and fqn '$fqn' is not available on the passed-in Liaison instance.");
}
/**
* Check if an instance of the called addon class exists on the Liaison object, based on the default `fqn` of the called addon class.
*
* @param $lia \Lia instance
* @return bool true if available, false if not
*/
static public function exists(\Lia $lia): bool {
$class = static::class;
$ref = new \ReflectionClass($class);
$fqn = $ref->getDefaultProperties()['fqn'];
try {
$addon = $lia->addon($fqn);
} catch (\Lia\Exception $e){
return false;
}
if ($addon instanceof $class)return true;
else return false;
}
public function __construct(?\Lia\Package $package=null){
$this->package = $package;
$this->lia = $package->lia ?? null;
if (!isset($this->name)){
$addon_name = strtolower(get_class($this));
$pos = strrpos($addon_name, '\\');
if ($pos!==false)$pos +=1;
$this->name = substr($addon_name, $pos);
}
if (!isset($this->fqn)){
throw new \Exception("Every addon MUST declare `public string \$fqn = 'fqn'`, where fqn SHOULD be like `vendor:package.addon_name`\n\n");
}
if ($package!=null){
$this->lia->addAddon($this, $this->fqn);
$package->addons[$this->name] = $this;
}
}
/**
* Called after the addon's parent package has finished loading. (configs loaded, bootstrapped, all other addons instantiated).
*
* onPackageAdded() has not been called yet.
*/
public function onParentReady(\Lia\Package $package){
}
/**
* Called after a Package is added to Liaison, after it has been fully initialized, after configs loaded, bootstrapped, all other addons instantiated, and `onParentReady()` called on each of its addons.
*
*/
public function onPackageAdded(\Lia\Package $package){
}
}