<?php
namespace Lia\Compo;
class PackageList extends \Lia\Compo {
protected $packages = [];
public function onReady(){
$lia = $this->lia;
$lia->addApi('lia:package.getCompo', [$this,'compo']);
$lia->addApiMethod('lia:package.getCompo', 'compo');
$lia->addApi('lia:package.add',[$this,'addPackage']);
$lia->addApiMethod('lia:package.add', 'addPackage');
$lia->addApi('lia:package.get',[$this,'getPackage']);
$lia->addApiMethod('lia:package.get', 'getPackage');
// $lia->addApi('lia:package.get_all',[$this,'getPackages']);
// $lia->addApiMethod('lia:package.get_all', 'getPackages');
}
public function addPackage($package, $namespace){
$this->packages[$namespace] = $package;
}
// public function getPackages(){
// return $this->packages;
// }
public function getPackage($name){
$package = $this->packages[$name] ?? null;
if ($package==null){
throw new \Lia\Exception("Package '{$name}' was not found.");
}
return $package;
}
/**
* Get a compo(nent) from available packages
*
* @param $name `namespace:ComponentClassName` <- `namespace:` is optional. `ComponentClassName` does NOT include the class's namespace
*/
public function compo($name){
$fqn = $name;
$parts=explode(':',$name);
$namespace=null;
$compoName=null;
if (count($parts)==2){
$namespace = $parts[0];
$compoName = $parts[1];
} else if (count($parts)==1){
$compoName = $parts[0];
}
$list = [];
$packageCount = 0;
// var_dump(array_keys($this->packages));
foreach ($this->packages as $name=>$package){
if (($namespace==null||strtolower($name)==strtolower($namespace))
){
$packageCount++;
$compo = $package->compo($compoName);
if ($compo!==null)$list[] = $compo;
}
}
if ($packageCount==0&&$namespace!=null){
throw new \Lia\Exception("There is no package for namespace '${namespace}', so compo for '${fqn}' can not be loaded.");
} else if (count($this->packages)==0){
throw new \Lia\Exception("There are no packages from which to laod components.");
} else if (count($list)>1){
throw new \Lia\Exception("Multiple compos were returned for '${fqn}'. Try providing a namespace like \$lia->compo('namespace:componame')");
} else if (count($list)==0){
throw new \Lia\Exception("No compos were found for '${fqn}', but the package for '${namespace}:' does exist.");
}
return $list[0];
}
}