|
- <?php
-
- namespace common\logic;
-
- use yii\base\ErrorException;
-
- class BaseService
- {
- public function getHierarchy(): array
- {
- return [
- FactoryInterface::class,
- SolverInterface::class,
- RepositoryInterface::class,
- BuilderInterface::class,
- ResolverInterface::class,
- UtilsInterface::class,
- ];
- }
-
- public function loadService(string $serviceClass)
- {
- if(!$this->respectHierarchy($serviceClass)) {
- throw new ErrorException('Le service '.$serviceClass.' ne peut pas être chargé ici.');
- }
-
- return new $serviceClass;
- }
-
- public function respectHierarchy(string $serviceClassAsked): bool
- {
- $domain = \Yii::$app->logic;
- $serviceCurrentClass = get_class($this);
- $levelHierarchyServiceAsked = $this->getServiceLevelHierarchy($serviceClassAsked);
- $levelHierarchyServiceCurrent = $this->getServiceLevelHierarchy($serviceCurrentClass);
-
- if($levelHierarchyServiceAsked < $levelHierarchyServiceCurrent) {
- return true;
- }
- elseif($levelHierarchyServiceAsked == $levelHierarchyServiceCurrent
- && $domain->getContainerLevelHierarchyByService($serviceClassAsked)
- < $domain->getContainerLevelHierarchyByService($serviceCurrentClass)) {
-
- return true;
- }
-
- return false;
- }
-
- public function getServiceLevelHierarchy(string $serviceClass): int
- {
- $hierarchyArray = $this->getHierarchy();
-
- foreach($hierarchyArray as $key => $interface) {
- if($this->classImplementsInterface($interface, $serviceClass)) {
- return $key;
- }
- }
-
- throw new ErrorException('Service introuvable dans la hiérarchie. Attention à bien ajouter
- FactoryInterface, SolverInterface ou BuilderInterface au service.');
- }
-
- public function isFactory(): bool
- {
- return $this->classImplementsInterface(FactoryInterface::class);
- }
-
- public function isSolver(): bool
- {
- return $this->classImplementsInterface(SolverInterface::class);
- }
-
- public function isBuilder(): bool
- {
- return $this->classImplementsInterface(BuilderInterface::class);
- }
-
- public function isResolver(): bool
- {
- return $this->classImplementsInterface(ResolverInterface::class);
- }
-
- public function isUtils(): bool
- {
- return $this->classImplementsInterface(UtilsInterface::class);
- }
-
- protected function classImplementsInterface(string $interface, $object = null)
- {
- if(is_null($object)) {
- $object = $this;
- }
-
- return in_array($interface, class_implements($object));
- }
- }
|