You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.4KB

  1. <?php
  2. namespace common\logic;
  3. use yii\base\ErrorException;
  4. abstract class AbstractService extends AbstractSingleton implements ServiceInterface
  5. {
  6. use ProducerContextTrait;
  7. protected function getHierarchy(): array
  8. {
  9. return [
  10. DefinitionInterface::class,
  11. SolverInterface::class,
  12. RepositoryQueryInterface::class,
  13. RepositoryInterface::class,
  14. NotifierInterface::class,
  15. BuilderInterface::class,
  16. ResolverInterface::class,
  17. GeneratorInterface::class,
  18. ManagerInterface::class,
  19. ];
  20. }
  21. protected function loadService(string $serviceClass)
  22. {
  23. if(!$this->respectHierarchy($serviceClass)) {
  24. throw new ErrorException('Le service '.$serviceClass.' ne peut pas être chargé ici.');
  25. }
  26. return $serviceClass::getInstance();
  27. }
  28. protected function loadDependencies(): void
  29. {
  30. }
  31. protected function respectHierarchy(string $serviceClassAsked): bool
  32. {
  33. $domain = \Yii::$app->logic;
  34. $serviceCurrentClass = get_class($this);
  35. $levelHierarchyServiceAsked = $this->getServiceLevelHierarchy($serviceClassAsked);
  36. $levelHierarchyServiceCurrent = $this->getServiceLevelHierarchy($serviceCurrentClass);
  37. if($levelHierarchyServiceAsked < $levelHierarchyServiceCurrent) {
  38. return true;
  39. }
  40. elseif($levelHierarchyServiceAsked == $levelHierarchyServiceCurrent
  41. && $domain->getModuleLevelHierarchyByService($serviceClassAsked)
  42. < $domain->getModuleLevelHierarchyByService($serviceCurrentClass)) {
  43. return true;
  44. }
  45. return false;
  46. }
  47. protected function getServiceLevelHierarchy(string $serviceClass): int
  48. {
  49. $hierarchyArray = $this->getHierarchy();
  50. foreach($hierarchyArray as $key => $interface) {
  51. if($this->classImplementsInterface($interface, $serviceClass)) {
  52. return $key;
  53. }
  54. }
  55. throw new ErrorException('Service introuvable dans la hiérarchie. Attention à bien ajouter
  56. FactoryInterface, SolverInterface ou BuilderInterface au service.');
  57. }
  58. protected function classImplementsInterface(string $interface, $object = null)
  59. {
  60. if(is_null($object)) {
  61. $object = $this;
  62. }
  63. return in_array($interface, class_implements($object));
  64. }
  65. }