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.

91 line
2.6KB

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