|
- <?php
-
- namespace common\logic;
-
- use yii\base\ErrorException;
-
- class BaseService
- {
- public function getHierarchy(): array
- {
- return [
- FactoryInterface::class,
- SolverInterface::class,
- BuilderInterface::class,
- ServiceInterface::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
- {
- $businessLogic = \Yii::$app->logic;
- $serviceCurrentClass = get_class($this);
- $levelHierarchyServiceAsked = $this->getServiceLevelHierarchy($serviceClassAsked);
- $levelHierarchyServiceCurrent = $this->getServiceLevelHierarchy($serviceCurrentClass);
-
- if($levelHierarchyServiceAsked < $levelHierarchyServiceCurrent) {
- return true;
- }
- elseif($levelHierarchyServiceAsked == $levelHierarchyServiceCurrent
- && $businessLogic->getContainerLevelHierarchyByService($serviceClassAsked)
- < $businessLogic->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 isService(): bool
- {
- return $this->classImplementsInterface(ServiceInterface::class);
- }
-
- protected function classImplementsInterface(string $interface, $object = null): bool
- {
- if(is_null($object)) {
- $object = $this;
- }
-
- return class_implements($object, $interface);
- }
- }
|