Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

97 lines
2.7KB

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