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.

90 line
2.5KB

  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. BuilderInterface::class,
  12. ServiceInterface::class,
  13. ];
  14. }
  15. public function loadService(string $serviceClass)
  16. {
  17. if(!$this->respectHierarchy($serviceClass)) {
  18. throw new ErrorException('Le service '.$serviceClass.' ne peut pas être chargé ici.');
  19. }
  20. return new $serviceClass;
  21. }
  22. public function respectHierarchy(string $serviceClassAsked): bool
  23. {
  24. $businessLogic = \Yii::$app->logic;
  25. $serviceCurrentClass = get_class($this);
  26. $levelHierarchyServiceAsked = $this->getServiceLevelHierarchy($serviceClassAsked);
  27. $levelHierarchyServiceCurrent = $this->getServiceLevelHierarchy($serviceCurrentClass);
  28. if($levelHierarchyServiceAsked < $levelHierarchyServiceCurrent) {
  29. return true;
  30. }
  31. elseif($levelHierarchyServiceAsked == $levelHierarchyServiceCurrent
  32. && $businessLogic->getContainerLevelHierarchyByService($serviceClassAsked)
  33. < $businessLogic->getContainerLevelHierarchyByService($serviceCurrentClass)) {
  34. return true;
  35. }
  36. return false;
  37. }
  38. public function getServiceLevelHierarchy(string $serviceClass): int
  39. {
  40. $hierarchyArray = $this->getHierarchy();
  41. foreach($hierarchyArray as $key => $interface) {
  42. if($this->classImplementsInterface($interface, $serviceClass)) {
  43. return $key;
  44. }
  45. }
  46. throw new ErrorException('Service introuvable dans la hiérarchie. Attention à bien ajouter
  47. FactoryInterface, SolverInterface ou BuilderInterface au service.');
  48. }
  49. public function isFactory(): bool
  50. {
  51. return $this->classImplementsInterface(FactoryInterface::class);
  52. }
  53. public function isSolver(): bool
  54. {
  55. return $this->classImplementsInterface(SolverInterface::class);
  56. }
  57. public function isBuilder(): bool
  58. {
  59. return $this->classImplementsInterface(BuilderInterface::class);
  60. }
  61. public function isService(): bool
  62. {
  63. return $this->classImplementsInterface(ServiceInterface::class);
  64. }
  65. protected function classImplementsInterface(string $interface, $object = null): bool
  66. {
  67. if(is_null($object)) {
  68. $object = $this;
  69. }
  70. return class_implements($object, $interface);
  71. }
  72. }