Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace NameSpace;
- class Factory
- {
- /** @var BoundaryDependencyOne $boundaryDependencyOne */
- private $boundaryDependencyOne;
- /** @var BoundaryDependencyTwo $boundaryDependencyTwo */
- private $boundaryDependencyTwo;
- public function __construct(
- BoundaryDependencyOne $boundaryDependencyOne = null,
- BoundaryDependencyTwo $boundaryDependencyTwo = null
- )
- {
- $this->boundaryDependencyOne = $boundaryDependencyOne;
- $this->boundaryDependencyTwo = $boundaryDependencyTwo;
- }
- /**
- * @param $method
- * @param array $args
- * @return null
- * @throws \ReflectionException
- */
- public function __call($method, $args = [])
- {
- $isGet = substr( $method, 0, 3 ) === "get";
- if (!$isGet) return null;
- $name = substr($method, 3, strlen($method) - 3);
- $dependencyNames = $this->getDependencyNames($name);
- $dependencies = array_map(function($dependencyName) {
- $methodName = "get$dependencyName";
- return $this->$methodName();
- }, $dependencyNames);
- return $this->getObject($name, ...$dependencies);
- }
- /**
- * @param $name
- * @return array|mixed
- * @throws \ReflectionException
- */
- private function getDependencyNames($name)
- {
- $simpleName = $this->getSimpleClassName($name);
- $reflection = new \ReflectionClass("\\NameSpace\\$simpleName");
- $constructor = $reflection->getConstructor();
- $params = ($constructor) ? $constructor->getParameters() : [];
- return array_map(function($param) {
- $name = $param->getClass()->name;
- return $this->getSimpleClassName($name);
- }, $params);
- }
- /**
- * @param $name
- * @return string
- */
- private function getSimpleClassName($name): string
- {
- $nameFragments = explode("\\", $name);
- return end($nameFragments);
- }
- /**
- * @param $class
- * @param mixed ...$dependencies
- * @return mixed
- */
- private function getObject($class, ...$dependencies)
- {
- $fullClassName = "\\NameSpace\\$class";
- $propertyName = lcfirst($class);
- if (! isset($this->$propertyName)) {
- $this->$propertyName = new $fullClassName(...$dependencies);
- }
- return $this->$propertyName;
- }
- }
Add Comment
Please, Sign In to add comment