|
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- <?php
-
- namespace common\logic;
-
- use yii\base\ErrorException;
-
- class BaseService
- {
- public function getHierarchy(): array
- {
- return [
- 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 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));
- }
- }
|