Guest User

Untitled

a guest
Dec 13th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. <?php
  2.  
  3. namespace NameSpace;
  4.  
  5. class Factory
  6. {
  7. /** @var BoundaryDependencyOne $boundaryDependencyOne */
  8. private $boundaryDependencyOne;
  9.  
  10. /** @var BoundaryDependencyTwo $boundaryDependencyTwo */
  11. private $boundaryDependencyTwo;
  12.  
  13. public function __construct(
  14. BoundaryDependencyOne $boundaryDependencyOne = null,
  15. BoundaryDependencyTwo $boundaryDependencyTwo = null
  16. )
  17. {
  18. $this->boundaryDependencyOne = $boundaryDependencyOne;
  19. $this->boundaryDependencyTwo = $boundaryDependencyTwo;
  20. }
  21.  
  22. /**
  23. * @param $method
  24. * @param array $args
  25. * @return null
  26. * @throws \ReflectionException
  27. */
  28. public function __call($method, $args = [])
  29. {
  30. $isGet = substr( $method, 0, 3 ) === "get";
  31.  
  32. if (!$isGet) return null;
  33.  
  34. $name = substr($method, 3, strlen($method) - 3);
  35. $dependencyNames = $this->getDependencyNames($name);
  36. $dependencies = array_map(function($dependencyName) {
  37. $methodName = "get$dependencyName";
  38. return $this->$methodName();
  39. }, $dependencyNames);
  40.  
  41. return $this->getObject($name, ...$dependencies);
  42. }
  43.  
  44. /**
  45. * @param $name
  46. * @return array|mixed
  47. * @throws \ReflectionException
  48. */
  49. private function getDependencyNames($name)
  50. {
  51. $simpleName = $this->getSimpleClassName($name);
  52. $reflection = new \ReflectionClass("\\NameSpace\\$simpleName");
  53. $constructor = $reflection->getConstructor();
  54. $params = ($constructor) ? $constructor->getParameters() : [];
  55.  
  56. return array_map(function($param) {
  57. $name = $param->getClass()->name;
  58.  
  59. return $this->getSimpleClassName($name);
  60. }, $params);
  61. }
  62.  
  63. /**
  64. * @param $name
  65. * @return string
  66. */
  67. private function getSimpleClassName($name): string
  68. {
  69. $nameFragments = explode("\\", $name);
  70.  
  71. return end($nameFragments);
  72. }
  73.  
  74. /**
  75. * @param $class
  76. * @param mixed ...$dependencies
  77. * @return mixed
  78. */
  79. private function getObject($class, ...$dependencies)
  80. {
  81. $fullClassName = "\\NameSpace\\$class";
  82. $propertyName = lcfirst($class);
  83.  
  84. if (! isset($this->$propertyName)) {
  85. $this->$propertyName = new $fullClassName(...$dependencies);
  86. }
  87.  
  88. return $this->$propertyName;
  89. }
  90. }
Add Comment
Please, Sign In to add comment