Package.php

<?php

namespace Lia;

class Package {

    /** example: package */
    public string $name;
    /** example: vendor:package */
    public string $fqn;

    /**
     * The root dir for the package
     */
    public ?string $dir = null;

    /**
     * Liaison object
     */
    public \Lia $lia;

    /** array of addons */
    public array $addons = [];

    /**
     * This really should be a dynamic property, but php 8.2 deprecates dynamic props. This is only used by Lia\Simple currently (Dec 8, 2022).
     * It really does make sense to have package-level configs though ... so that's another reason to leave this prop.
     */
    public $config = [];

    /**
     * @param $liaison a lia object
     * @param $fqn a string like `vendor:package_name`
     * @param $dir the root dir of this package
     */
    public function __construct(\Lia $liaison, string $fqn, ?string $dir=null){
        $this->lia = $liaison;
        $this->dir = $dir ?? $this->dir;
        $this->fqn = $fqn ?? $this->fqn;
        $this->lia->fqn_packages[$this->fqn] = $this;
        $pos = strpos($this->fqn, ':');
        if ($pos!==false)$pos +=1;
        $short_name = substr($this->fqn, $pos);
        $this->name = $short_name;
        $this->lia->packages[$short_name] = $this;
        $this->bootstrap();
    }

    /**
     * `require()` the bootstrap.php file in the package's root dir, if it exists.
     *
     * It's called after the Package class has been initialized, with name, dir, lia, and fqn set. Addons are not yet loaded.  
     * If you use addons, call '$this->load_addons()' in your bootstrap.php file
     * @NOTE subclass `\Lia\Package` or `\Lia\Package\Server` and implement a custom 'bootstrap()' method.
     */
    protected function bootstrap(){
        if (file_exists($this->dir.'/bootstrap.php')){
            require($this->dir.'/bootstrap.php');
        }
    }

    /**
     * foreach $addon, $addon->init_lia
     */
    public function init_lia(){
        foreach ($this->addons as $name=>$a){
            // echo "\n- $name: init_lia";
            $a->init_lia($this);
        }
    }


    public function load_addons($sub_dir = 'addon'){
        $dir = $this->dir.'/'.$sub_dir;
        
        $classes = \Lia\Utility\ClassFinder::classesFromDir($dir);
        if (count($classes)==0)return;
        $addons = [];
        foreach ($classes as $info){
            // if (!in_array('Lia\\iCore\\Compo',$info['interfaces']))continue;
            $className = $info['class'];
            // if (!class_exists($className,true))continue;
            $addon = new $className($this);
        }
    }

    public function ready(){
        foreach ($this->addons as $a){
            $a->onPackageReady($this);
        }
    }

    public function dir($sub_dir){
        return $this->dir.'/'.$sub_dir.'/';
    }

}