Beispiel #1
0
 /**
  * Maps two object together, a map should exist.
  *
  * @param $source
  * @param $destination
  *
  * @return object
  * @throws InvalidClassConstructorException
  */
 public function map($source, $destination)
 {
     if (is_string($destination)) {
         $destinationRef = new \ReflectionClass($destination);
         if ($destinationRef->getConstructor() && $destinationRef->getConstructor()->getNumberOfRequiredParameters() > 0) {
             throw new InvalidClassConstructorException($destination);
         }
         $destination = $destinationRef->newInstance();
     }
     $map = $this->getMap($this->guessType($source), $this->guessType($destination));
     $fieldAccessors = $map->getFieldAccessors();
     $fieldFilters = $map->getFieldFilters();
     foreach ($fieldAccessors as $path => $fieldAccessor) {
         $value = $fieldAccessor->getValue($source);
         if (isset($fieldFilters[$path])) {
             if (($filter = $fieldFilters[$path]) instanceof AbstractMappingFilter) {
                 $filter->setMapper($this);
             }
             $value = $filter->filter($value);
         }
         if ($map->getSkipNull() && is_null($value)) {
             continue;
         }
         $propertyAccessor = PropertyAccess::createPropertyAccessor();
         if ($map->getOverwriteIfSet()) {
             $propertyAccessor->setValue($destination, $path, $value);
         } else {
             if ($propertyAccessor->getValue($destination, $path) == null) {
                 $propertyAccessor->setValue($destination, $path, $value);
             }
         }
     }
     return $destination;
 }
 /**
  * Test handling of attributes of the DateTime type.
  */
 public function testDateTime()
 {
     // Add a mostly dummy configuration. We are not going to read or write any files here.
     // The important part is the accessors part.
     $config = new Config(array('inputFile' => null, 'outputDir' => null, 'constructorParamsDefaultToNull' => true));
     $complexType = new ComplexType($config, 'ComplexTypeTestClass');
     $complexType->addMember('dateTime', 'dateTimeAttribute', false);
     $this->generateClass($complexType);
     $this->assertClassExists('ComplexTypeTestClass');
     $this->assertClassHasAttribute('dateTimeAttribute', 'ComplexTypeTestClass');
     $this->assertClassHasMethod('ComplexTypeTestClass', 'getDateTimeAttribute');
     $this->assertClassHasMethod('ComplexTypeTestClass', 'setDateTimeAttribute');
     $object = new \ComplexTypeTestClass(new \DateTime());
     $class = new \ReflectionClass($object);
     $this->assertMethodParameterHasType($class->getConstructor(), 'dateTimeAttribute', 'DateTime');
     $this->assertMethodParameterDocBlockHasType($class->getConstructor(), 'dateTimeAttribute', '\\DateTime');
     $this->assertMethodHasReturnType($class->getMethod('getDateTimeAttribute'), '\\DateTime');
     $this->assertMethodParameterHasType($class->getMethod('setDateTimeAttribute'), 'dateTimeAttribute', 'DateTime');
     $this->assertMethodParameterDocBlockHasType($class->getMethod('setDateTimeAttribute'), 'dateTimeAttribute', '\\DateTime');
     // Using reflection to set up bad datetime value as like SoapClass does it
     $property = 'dateTimeAttribute';
     $badDateTime = 'noDate';
     $this->setObjectProperty($object, $property, $badDateTime);
     $this->assertFalse($object->getDateTimeAttribute());
     // Test passing variable datetime formats available in SOAP, http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/#dateTime
     $now = new \DateTime();
     foreach (array('Y-m-d\\TH:i:s', 'Y-m-d\\TH:i:sP', 'Y-m-d\\TH:i:s.u', 'Y-m-d\\TH:i:s.uP', 'Y-m-d\\TH:i:s\\Z', 'Y-m-d\\TH:i:s.u\\Z') as $format) {
         $this->setObjectProperty($object, $property, $now->format($format));
         $this->assertInstanceOf('\\DateTime', $object->getDateTimeAttribute());
     }
 }
Beispiel #3
0
 /**
  * {@inheritdoc}
  */
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $class = $input->getArgument('factory');
     $class = str_replace('/', '\\', $class);
     if (false === class_exists($class)) {
         throw new \Exception(sprintf('Class %s not found', $class));
     }
     $rfl = new \ReflectionClass($class);
     if (null !== $rfl->getConstructor() && 0 < $rfl->getConstructor()->getNumberOfRequiredParameters()) {
         throw new \Exception('Can\'t instanciate adapter factory %s, constructor shouldn\'t need required parameters');
     }
     $factory = new $class();
     if (false === $factory instanceof AdapterFactory) {
         throw new \Exception('Your adapter factory should implements Gaufrette\\TestSuite\\Adapter\\AdapterFactory');
     }
     $exit = 0;
     foreach ($this->tests->all() as $test) {
         $output->writeln('');
         $adapter = $factory->create();
         $result = $this->runTest($test, $adapter, $output);
         $factory->destroy();
         $exit = true === $result ? $exit : 1;
     }
     $output->writeln('');
     return $exit;
 }
 /**
  * @param null|string|CrudControllerInterface $controller
  * @return CrudControllerInterface
  * @throws ControllerNotFoundException
  */
 public function resolve($controller)
 {
     if (null === $controller) {
         $controller = $this->defaultController;
     }
     $name = $controller;
     if (is_string($controller)) {
         if (isset($this->resolved[$controller])) {
             return $this->resolved[$controller];
         }
         if ($this->container->has($controller)) {
             $controller = $this->container->get($controller);
         } elseif (class_exists($controller, true)) {
             $refl = new \ReflectionClass($controller);
             if ($refl->implementsInterface('Bravesheep\\CrudifyBundle\\Controller\\CrudControllerInterface')) {
                 if ($refl->getConstructor() === null || $refl->getConstructor()->getNumberOfRequiredParameters() === 0) {
                     $controller = $refl->newInstance();
                     $controller->setContainer($this->container);
                 }
             }
         }
     }
     if (!$controller instanceof CrudControllerInterface) {
         throw new ControllerNotFoundException("Could not resolve controller specification to controller");
     }
     if (is_string($name)) {
         $this->resolved[$name] = $controller;
     }
     return $controller;
 }
Beispiel #5
0
 /**
  * Derives properties from constructor, public instance variables, getters and setters.
  *
  * @param object|null $object If provided, dynamic (run-time) variables are read as well
  * @return \watoki\collections\Map|Property[] indexed by property name
  */
 public function readInterface($object = null)
 {
     $properties = new Map();
     if ($this->class->getConstructor()) {
         foreach ($this->class->getConstructor()->getParameters() as $parameter) {
             $this->accumulate($properties, new property\ConstructorProperty($this->factory, $this->class->getConstructor(), $parameter));
         }
     }
     $declaredProperties = array();
     foreach ($this->class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
         if (!$property->isStatic()) {
             $declaredProperties[] = $property->name;
             $this->accumulate($properties, new property\InstanceVariableProperty($this->factory, $property));
         }
     }
     if (is_object($object)) {
         foreach ($object as $name => $value) {
             if (!in_array($name, $declaredProperties)) {
                 $this->accumulate($properties, new property\DynamicProperty($this->factory, new \ReflectionClass($object), $name));
             }
         }
     }
     foreach ($this->class->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
         if (property\AccessorProperty::isAccessor($method) && !$method->isStatic()) {
             $this->accumulate($properties, new property\AccessorProperty($this->factory, $method));
         }
     }
     return $properties;
 }
Beispiel #6
0
 /**
  * Constructor
  *
  * @param string|object $base_class Class name of the base class, or an instance
  * @param array $constructor_args (Optional) Arguments to pass to the constructor of the base class
  * @param array $constants (Optional) Constants to override
  */
 public function __construct($base_class, array $constructor_args = array(), array $constants = array())
 {
     // @codeCoverageIgnoreStart
     if (PHP_VERSION_ID < 50300) {
         trigger_error(get_class() . ': This class requires PHP version 5.3 or higher.', E_USER_ERROR);
     }
     // @codeCoverageIgnoreEnd
     if (is_object($base_class) && count($constructor_args)) {
         throw new Mollie_Testing_Exception('Unused constructor arguments for passed instance of "' . get_class($base_class) . '".');
     }
     // If it's an instance, just accept it
     if (is_object($base_class)) {
         $this->_base_class = $base_class;
     } elseif (!class_exists($base_class)) {
         throw new Mollie_Testing_Exception("Base class '{$base_class}' does not exist.");
     } else {
         $ref = new ReflectionClass($base_class);
         if ($ref->isAbstract()) {
             $ref = new ReflectionClass($this->createDerivedClass($base_class));
         }
         if ($ref->getConstructor() && count($constructor_args) < $ref->getConstructor()->getNumberOfRequiredParameters()) {
             throw new Mollie_Testing_Exception($ref->getConstructor()->getNumberOfRequiredParameters() . " constructor arguments required for '{$base_class}::__construct(...)'.");
         }
         $this->_base_class = sizeof($constructor_args) ? $ref->newInstanceArgs($constructor_args) : $ref->newInstance();
     }
 }
 private function generateCode($classes, $controllerName)
 {
     $methods = [];
     $comments = [];
     foreach ($classes as $item) {
         if (false === class_exists($item)) {
             $comments[] = sprintf('Class %s does not exist', $item);
             continue;
         }
         $reflection = new \ReflectionClass($item);
         if ($reflection->getConstructor() && 0 !== $reflection->getConstructor()->getNumberOfRequiredParameters()) {
             $comments[] = sprintf('Class %s has a required constructor argument', $item);
             continue;
         }
         if (false === $reflection->hasMethod('getDefaultView')) {
             $comments[] = sprintf('Class %s has no default view', $item);
             continue;
         }
         list($name) = array_reverse(explode("\\", $item));
         $template = $reflection->newInstance()->getDefaultView();
         $methods[] = ['name' => lcfirst($name), 'class' => $item, 'template' => $template];
     }
     $code = '<?php' . "\n\n" . '// THIS FILE IS GENERATED DURING THE CACHE WARMUP, DO NOT MODIFY' . "\n" . 'class %s extends \\Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller' . "\n" . '{%s}';
     $code = sprintf($code, $controllerName, "\n\n\t" . ($comments ? implode("\n\t", $comments) . "\n\n\t" : '') . implode("\n\t", array_map(function ($item) {
         $key = false === strpos($item['class'], "PagePart") ? 'page' : 'resource';
         return sprintf('public function %sAction()' . "\n\t" . '{' . "\n\t\t" . 'return $this->render("%s", [' . "\n\t\t\t" . '"%s" => new \\%s,' . "\n\t\t" . ']);' . "\n\t" . "}" . "\n", $item['name'], $item['template'], $key, $item['class']);
     }, $methods)) . "\n");
     $code = str_replace("\t", "    ", $code);
     return $code;
 }
 private function instantinate($class_name)
 {
     if (array_key_exists($class_name, $this->class_dictionary)) {
         $class_name = $this->class_dictionary[$class_name];
     }
     $class = new ReflectionClass($class_name);
     $parameters = array();
     $constructor = $class->getConstructor();
     if ($constructor != null) {
         $parameters = $class->getConstructor()->getParameters();
     }
     $dependencies = array();
     foreach ($parameters as $value) {
         $className = "";
         if ($value->getClass() != null) {
             $className = $value->getClass()->getName();
         }
         $parameterName = $value->getName();
         if (array_key_exists($className, $this->instance_dictionary)) {
             $dependencies[] = $this->instance_dictionary[$className];
         } elseif (array_key_exists($parameterName, $this->var_dictionary)) {
             if (!is_string($this->var_dictionary[$parameterName])) {
                 $dependencies[] = $this->var_dictionary[$parameterName];
             } else {
                 $dependencies[] = $this->get($this->var_dictionary[$parameterName]);
             }
         } elseif (array_key_exists($className, $this->class_dictionary)) {
             $dependencies[] = $this->get($className);
         } else {
             throw new IocClassNotFounException($class_name, $className, $parameterName);
         }
     }
     return call_user_func_array(array(new ReflectionClass($class_name), 'newInstance'), $dependencies);
 }
 public function testGeneratedCode()
 {
     // Test that enums are created correctly.
     //
     // the MS-SSNWS contains enumerations with names that collide with PHP
     // keywords. This test ensures that they are created correctly.
     //
     // Load the code. This ensures that the syntax of the generated code is
     // valid.
     // We do not call the service here. It is not necessary for the check
     // at hand and we do not have a valid endpoint for the service either.
     // Create an instance of a class containing problematic constants. This also autoloads it.
     $typeEnum = new \sqlDbTypeEnum();
     // If we got this far and loaded the class without parse errors we should be good.
     $this->assertTrue(true);
     // Test that classes with datetimes are created correctly.
     //
     // This should be in a separate test method. This would however cause
     // code generated to run twice and classes would be generated twice as
     // setUp() is called twice. Since the first part of the test loads all
     // the classes the second round would add a suffix to class names to
     // avoid conflicts.
     //
     // This we test for multiple aspects in the same method. Going forward
     // we should consider separating generated code between methods - e.g.
     // by adding the test method as a namespace.
     $this->assertGeneratedClassExists('DayAsNumber');
     $object = new \DayAsNumber(new \DateTime());
     $class = new \ReflectionClass($object);
     $this->assertMethodParameterHasType($class->getConstructor(), 'day', 'DateTime');
     $this->assertMethodParameterDocBlockHasType($class->getConstructor(), 'day', '\\DateTime');
 }
Beispiel #10
0
 /**
  * Makes an instance of a class
  *
  * @param string $className Class name
  * @return object Class instance
  */
 public function make($className)
 {
     // Create a reflection to access the class properties
     $reflection = new \ReflectionClass($className);
     // If the class has no constructor, just return a new instance
     $constructor = $reflection->getConstructor();
     if (is_null($constructor)) {
         return new $className();
     }
     // Or get the constructor parameters and instance dependencies
     $dependencies = [];
     $parameters = $reflection->getConstructor()->getParameters();
     foreach ($parameters as $param) {
         $class = $param->getClass();
         if ($class && $class->getName() === 'Laito\\App') {
             // If the dependency is the app itself, inject the current instance
             $dependencies[] = $this;
         } else {
             // Otherwise, inject the instantiated dependency or a null value
             $dependencies[] = $class ? $this->make($class->name) : 'NULL';
         }
     }
     // Return the class instance
     $instance = $reflection->newInstanceArgs($dependencies);
     // If the class has a boot method, run it
     if (method_exists($instance, 'boot')) {
         $instance->boot();
     }
     // Return instance
     return $instance;
 }
 /**
  * @return \ReflectionParameter[]
  */
 function getReflectionParameters()
 {
     $reflConstructor = $this->reflClass->getConstructor();
     if (NULL === $reflConstructor) {
         return array();
     }
     return $reflConstructor->getParameters();
 }
 /**
  * Fetches constructor args (array of ReflectionParameter) from the reflected class
  * and set them as an associative array
  */
 public function initConstructorArgs()
 {
     $constructor = $this->reflected->getConstructor();
     if (!is_null($constructor)) {
         // Index parameters by their names
         foreach ($constructor->getParameters() as $param) {
             $this->constructorArgs[$param->getName()] = $param;
         }
     }
 }
Beispiel #13
0
 /**
  * Get Class definition for constructor parameter.
  *
  * @param \ReflectionClass $parameterClass
  *
  * @return mixed|null|object
  */
 private function getClassDefinition(\ReflectionClass $parameterClass)
 {
     $parameterClassName = $parameterClass->getName();
     $entryReference = new \ReflectionClass($parameterClass->getName());
     $argumentParams = false;
     if ($entryReference->getConstructor()) {
         $argumentParams = $entryReference->getConstructor()->getParameters();
     }
     return $argumentParams ? $this->get($parameterClassName) : new $parameterClassName();
 }
 /**
  * Fetches constructor args (array of ReflectionParameter) from the reflected class
  * and set them as an associative array
  *
  * Convert the parameter names to camelCase for classes that have contructor
  * params defined in snake_case for consistency with the options
  */
 public function initConstructorArgs()
 {
     $constructor = $this->reflected->getConstructor();
     if (!is_null($constructor)) {
         // Index parameters by their names
         foreach ($constructor->getParameters() as $param) {
             $name = Util::snakeToCamelCase($param->getName());
             $this->constructorArgs[$name] = $param;
         }
     }
 }
 /**
  * Fetches constructor args (array of ReflectionParameter) from the reflected class
  * and set them as an associative array
  *
  * Convert the parameter names to camelCase for classes that have contructor
  * params defined in snake_case for consistency with the options
  */
 public function initConstructorArgs()
 {
     $constructor = $this->reflected->getConstructor();
     $nameConverter = new CamelCaseToSnakeCaseNameConverter();
     if (!is_null($constructor)) {
         // Index parameters by their names
         foreach ($constructor->getParameters() as $param) {
             $this->constructorArgs[$nameConverter->denormalize($param->getName())] = $param;
         }
     }
 }
Beispiel #16
0
 /**
  * Generic constructor for all Singleton classes
  * @param string $class
  * @param float $ts
  * @param array $args
  * @return \CloudFramework\Patterns\Schemas\SingletonInterface
  */
 private static function instanceClass($class, $ts, array $args = array())
 {
     $reflectionClass = new \ReflectionClass($class);
     /** @var \CloudFramework\Patterns\Schemas\SingletonInterface $instanceClass */
     if (null !== $reflectionClass->getConstructor() && $reflectionClass->getConstructor()->getNumberOfParameters() > 0) {
         $instanceClass = $reflectionClass->newInstanceArgs($args);
     } else {
         $instanceClass = $reflectionClass->newInstance();
     }
     self::initializeInstance($ts, $reflectionClass, $instanceClass);
     unset($reflectionClass);
     return $instanceClass;
 }
Beispiel #17
0
 /**
  * Resolves the dependencies recursively.
  */
 protected function reflect($key)
 {
     $reflector = new \ReflectionClass($key);
     if (!$reflector->getConstructor()) {
         return new $key();
     }
     $parameters = $reflector->getConstructor()->getParameters();
     $dependencies = [];
     foreach ($parameters as $parameter) {
         $className = $parameter->getClass()->getName();
         $dependencies[] = $this->reflect($className);
     }
     return $reflector->newInstanceArgs($dependencies);
 }
 /**
  * @param FormEvent $e
  */
 public function setEntityAsObject(FormEvent $e)
 {
     $form = $e->getTarget();
     if (!$form instanceof FormInterface) {
         return;
     }
     $config = $e->getConfiguration();
     if (!$config || !$config->getEntity()) {
         return;
     }
     $rc = new \ReflectionClass($config->getEntity());
     $hasConstructorparams = $rc->getConstructor() && $rc->getConstructor()->getNumberOfParameters() ? true : false;
     $instance = $hasConstructorparams ? $rc->newInstanceWithoutConstructor() : $rc->newInstance();
     $form->setObject($instance);
 }
Beispiel #19
0
 private function getContructArguments($classname)
 {
     $arguments = [];
     $reflector = new \ReflectionClass($classname);
     if ($reflector->getConstructor()) {
         foreach ($reflector->getConstructor()->getParameters() as $param) {
             $classname = $param->getClass()->name;
             if ($classname == 'Buuum\\Config') {
                 $classname = 'config';
             }
             $arguments[] = $classname;
         }
     }
     return $arguments;
 }
Beispiel #20
0
 /**
  * Creates an object instance of the requested class, optionally passing additional constructor arguments
  *
  * @param $requestedClass
  * @param ...$arguments
  * @return mixed|object
  */
 public final function getInstance($requestedClass, ...$arguments)
 {
     if (isset($this->singletons[$requestedClass])) {
         return $this->singletons[$requestedClass];
     }
     $useSingleton = false;
     // Check for singletons first as they should trump previous registrations of non
     // singleton mappings.
     if (isset($this->concreteClassMappings['_' . $requestedClass])) {
         $class = $this->concreteClassMappings['_' . $requestedClass];
         $useSingleton = true;
     } elseif (isset($this->concreteClassMappings[$requestedClass])) {
         $class = $this->concreteClassMappings[$requestedClass];
     } else {
         $class = $requestedClass;
     }
     $reflection = new \ReflectionClass($class);
     if ($reflection->isAbstract()) {
         throw new ClassMappingException($class);
     }
     $constructor = $reflection->getConstructor();
     if ($constructor == null) {
         // No defined constructor so exit simply with a new instance.
         $instance = $reflection->newInstanceArgs($arguments);
     } else {
         $instance = $this->generateInstanceFromConstructor($reflection, $constructor, $arguments);
     }
     if ($useSingleton) {
         $this->singletons[$requestedClass] = $instance;
     }
     return $instance;
 }
 public function testResultSetConstruction()
 {
     $resultSet = ResultSet::create(array('part1', 'part2', 'part3'), 'parts');
     self::assertInstanceOf('DrestCommon\\ResultSet', $resultSet);
     $refl = new \ReflectionClass('DrestCommon\\ResultSet');
     self::assertTrue($refl->getConstructor()->isPrivate());
 }
Beispiel #22
0
 public static function resolve($type, $constructorArguments = [])
 {
     $resolvedClass = self::getResolvedClassName($type);
     if ($resolvedClass === null) {
         throw new exceptions\ResolutionException("Could not resolve dependency {$type}");
     }
     $reflection = new \ReflectionClass($resolvedClass);
     if ($reflection->isAbstract()) {
         throw new exceptions\ResolutionException("Abstract class {$reflection->getName()} cannot be instantiated. " . "Please provide a binding to an implementation.");
     }
     $constructor = $reflection->getConstructor();
     $instanceParameters = [];
     if ($constructor != null) {
         $parameters = $constructor->getParameters();
         foreach ($parameters as $parameter) {
             $class = $parameter->getClass();
             if (isset($constructorArguments[$parameter->getName()])) {
                 $instanceParameters[] = $constructorArguments[$parameter->getName()];
             } else {
                 $instanceParameters[] = $class ? self::resolve($class->getName()) : null;
             }
         }
     }
     return $reflection->newInstanceArgs($instanceParameters);
 }
 /**
  * Creates a new instance of the cacheable object or returns an already
  * cached one
  *
  * The parameters of this method are derived from the constructor of the
  * cacheable class. Additionally, the following parameters are dynamically
  * added:
  *
  * @param bool $fetch If <var>true</var> the object’s <var>fetch()</var>
  *        method will be called
  * @param bool $bypassCache If <var>true</var> the cache will not be hit
  * @return mixed A new object or a matching cached one
  */
 public static function create()
 {
     $args = func_get_args();
     $className = empty(self::$className) ? get_class() : self::$className;
     $class = new \ReflectionClass($className);
     $constructor = $class->getConstructor();
     $arity = $constructor->getNumberOfParameters();
     if (sizeof($args) < $arity) {
         array_fill(0, $arity, null);
     }
     $bypassCache = sizeof($args) > $arity + 1 ? array_pop($args) : false;
     $fetch = sizeof($args) > $arity ? array_pop($args) : true;
     $object = $class->newInstanceWithoutConstructor();
     $constructor->setAccessible(true);
     $constructor->invokeArgs($object, $args);
     $cachedObject = $object->cachedInstance();
     if ($cachedObject != null && !$bypassCache) {
         $object = $cachedObject;
     }
     if ($fetch && ($bypassCache || !$object->isFetched())) {
         $object->fetch();
         $object->cache();
     }
     return $object;
 }
Beispiel #24
0
 /**
  * @dataProvider getClass
  */
 public function testGetterAndSetter($class, $constructorParameterList)
 {
     $reflexionClass = new \ReflectionClass($class);
     if ($reflexionClass->getConstructor()) {
         $instance = $reflexionClass->newInstanceArgs($constructorParameterList);
     } else {
         $instance = $reflexionClass->newInstance();
     }
     $propertyList = $reflexionClass->getProperties();
     foreach ($propertyList as $property) {
         $name = ucfirst($property->getName());
         $property->setAccessible(true);
         $getter = 'get' . $name;
         $setter = 'set' . $name;
         if ($reflexionClass->hasMethod($setter)) {
             $type = $this->guessParamType($reflexionClass->getMethod($setter));
             if (isset($this->valueList[$type])) {
                 $value = $this->valueList[$type];
                 $instance->{$setter}($value[0]);
                 // test setter
                 $this->assertEquals($property->getValue($instance), $value[0]);
                 if ($reflexionClass->hasMethod($getter)) {
                     $property->setValue($instance, $value[1]);
                     // test getter
                     $this->assertEquals($instance->{$getter}(), $value[1]);
                 }
             }
         }
     }
 }
 /**
  * call back for mocking the object factory
  * @return object fixture objects ...
  * @author Robert Lemke <*****@*****.**>
  */
 public function objectManagerCallback()
 {
     $arguments = array_merge(func_get_args(), array($this->mockObjectManager));
     $objectName = array_shift($arguments);
     $class = new \ReflectionClass($objectName);
     return $class->getConstructor() !== null ? $class->newInstanceArgs($arguments) : $class->newInstance();
 }
Beispiel #26
0
 /**
  * 自动绑定(Autowiring)自动解析(Automatic Resolution)
  *
  * @param string $className
  * @return object
  * @throws Exception
  */
 public function build($className)
 {
     var_dump($className);
     // 如果是匿名函数(Anonymous functions),也叫闭包函数(closures)
     if ($className instanceof \Closure) {
         // 执行闭包函数,并将结果
         return $className($this);
     }
     /** @var ReflectionClass $reflector */
     $reflector = new \ReflectionClass($className);
     // 检查类是否可实例化, 排除抽象类abstract和对象接口interface
     if (!$reflector->isInstantiable()) {
         throw new Exception("Can't instantiate this.");
     }
     /** @var ReflectionMethod $constructor 获取类的构造函数 */
     $constructor = $reflector->getConstructor();
     // 若无构造函数,直接实例化并返回
     if (is_null($constructor)) {
         return new $className();
     }
     // 取构造函数参数,通过 ReflectionParameter 数组返回参数列表
     $parameters = $constructor->getParameters();
     // 递归解析构造函数的参数
     $dependencies = $this->getDependencies($parameters);
     // 创建一个类的新实例,给出的参数将传递到类的构造函数。
     return $reflector->newInstanceArgs($dependencies);
 }
Beispiel #27
0
 /**
  * @param $name
  * @return mixed
  * @throws \Exception
  */
 public function getInstance($name)
 {
     if (!is_string($name)) {
         throw new \Exception('Name must be a string');
     }
     $name = rtrim($name, '\\');
     if (isset($this->instance[$name])) {
         return $this->instance[$name]();
     } else {
         $reflectionClass = new \ReflectionClass($name);
         if (!$reflectionClass->isInstantiable()) {
             throw new \Exception('Class ' . $name . ' is not instantiable');
         }
         $constructor = $reflectionClass->getConstructor();
         if (!is_null($constructor)) {
             $parameters = $constructor->getParameters();
             $params = $this->getReflectionParametersValues($parameters);
         } else {
             $params = array();
         }
         $this->setInstance($name, function () use($reflectionClass, $params) {
             return $reflectionClass->newInstanceArgs($params);
         });
         return $this->getInstance($name);
     }
 }
 private function makeInstanceFromClassName($className, array $alreadySeen)
 {
     $className = $this->resolveClassName($className);
     try {
         $refl = new ReflectionClass($className);
     } catch (ReflectionException $re) {
         throw new Core_Foundation_IoC_Exception(sprintf('This doesn\'t seem to be a class name: `%s`.', $className));
     }
     $args = array();
     if ($refl->isAbstract()) {
         throw new Core_Foundation_IoC_Exception(sprintf('Cannot build abstract class: `%s`.', $className));
     }
     $classConstructor = $refl->getConstructor();
     if ($classConstructor) {
         foreach ($classConstructor->getParameters() as $param) {
             $paramClass = $param->getClass();
             if ($paramClass) {
                 $args[] = $this->doMake($param->getClass()->getName(), $alreadySeen);
             } elseif ($param->isDefaultValueAvailable()) {
                 $args[] = $param->getDefaultValue();
             } else {
                 throw new Core_Foundation_IoC_Exception(sprintf('Cannot build a `%s`.', $className));
             }
         }
     }
     if (count($args) > 0) {
         return $refl->newInstanceArgs($args);
     } else {
         // newInstanceArgs with empty array fails in PHP 5.3 when the class
         // doesn't have an explicitly defined constructor
         return $refl->newInstance();
     }
 }
 public function callConstructor()
 {
     $parent = new \ReflectionClass(parent::class);
     if ($parent->getConstructor()) {
         parent::__construct();
     }
 }
 /**
  * @param array    $schema
  * @param PhpClass $class
  */
 protected function generateConstructor(array $schema, PhpClass $class)
 {
     $constructorParams = [];
     $constructorBody = [];
     if (!empty($schema['inherit'])) {
         $parent = new \ReflectionClass($schema['inherit']);
         $parentConstructor = $parent->getConstructor();
         if ($parentConstructor) {
             $params = $parentConstructor->getParameters();
             $callParamsDef = [];
             foreach ($params as $param) {
                 $constructorParams[] = PhpParameter::fromReflection($param);
                 $callParamsDef[] = '$' . $param->getName();
             }
             $constructorBody[] = sprintf('parent::__construct(%s);', implode(', ', $callParamsDef));
         }
     }
     foreach ($schema['addremove'] as $fieldName => $config) {
         $constructorBody[] = '$this->' . $fieldName . ' = new \\Doctrine\\Common\\Collections\\ArrayCollection();';
     }
     $constructor = $this->generateClassMethod('__construct', implode("\n", $constructorBody));
     foreach ($constructorParams as $constructorParam) {
         $constructor->addParameter($constructorParam);
     }
     $class->setMethod($constructor);
 }