public function testClassDeviceResult()
 {
     $class = new \ReflectionClass('UAParser\\Result\\Device');
     $this->assertTrue($class->hasProperty('model'), 'property family does not exist anymore');
     $this->assertTrue($class->hasProperty('brand'), 'property major does not exist anymore');
     $this->assertTrue($class->hasProperty('family'), 'property family does not exist anymore');
 }
Example #2
0
 /**
  * {@inheritdoc}
  */
 public function process(ContainerBuilder $container)
 {
     foreach ($container->findTaggedServiceIds('mautic.event_subscriber') as $id => $tags) {
         $definition = $container->findDefinition($id);
         $classParents = class_parents($definition->getClass());
         if (!in_array(CommonSubscriber::class, $classParents)) {
             continue;
         }
         $definition->addMethodCall('setTemplating', [new Reference('mautic.helper.templating')]);
         $definition->addMethodCall('setRequest', [new Reference('request_stack')]);
         $definition->addMethodCall('setSecurity', [new Reference('mautic.security')]);
         $definition->addMethodCall('setSerializer', [new Reference('jms_serializer')]);
         $definition->addMethodCall('setSystemParameters', [new Parameter('mautic.parameters')]);
         $definition->addMethodCall('setDispatcher', [new Reference('event_dispatcher')]);
         $definition->addMethodCall('setTranslator', [new Reference('translator')]);
         $definition->addMethodCall('setEntityManager', [new Reference('doctrine.orm.entity_manager')]);
         $definition->addMethodCall('setRouter', [new Reference('router')]);
         $class = $definition->getClass();
         $reflected = new \ReflectionClass($class);
         if ($reflected->hasProperty('logger')) {
             $definition->addMethodCall('setLogger', [new Reference('monolog.logger.mautic')]);
         }
         // Temporary, for development purposes
         if ($reflected->hasProperty('factory')) {
             $definition->addMethodCall('setFactory', [new Reference('mautic.factory')]);
         }
         if (in_array(WebhookSubscriberBase::class, $classParents)) {
             $definition->addMethodCall('setWebhookModel', [new Reference('mautic.webhook.model.webhook')]);
         }
         $definition->addMethodCall('init');
     }
 }
 /**
  * Magic function which handles the properties accessibility.
  * @param string $propertyName The property name.
  */
 public function __get($propertyName)
 {
     switch ($propertyName) {
         case '_baseExtendableObject':
             return $this->_baseExtendableObject;
         default:
             $class = new \ReflectionClass($this);
             if ($class->hasProperty($propertyName)) {
                 $property = $class->getProperty($propertyName);
                 $property->setAccessible(true);
                 return $property->getValue($this);
             } else {
                 if ($class->hasProperty('_' . $propertyName)) {
                     $property = $class->getProperty('_' . $propertyName);
                     $property->setAccessible(true);
                     return $property->getValue($this);
                 } else {
                     $baseClass = new \ReflectionClass($_baseExtendableObject);
                     $method = $baseClass->getMethod('__get');
                     return $method->invoke($this, $propertyName);
                 }
             }
             return null;
     }
 }
 /**
  */
 public function testAddProperty()
 {
     $prop = new ReflectionProperty('test');
     $this->assertFalse($this->object->hasProperty('test'));
     $this->object->addProperty($prop);
     $this->assertTrue($this->object->hasProperty('test'));
 }
 public function testContracts()
 {
     $this->assertTrue($this->reflectedObject->isAbstract());
     $this->assertTrue($this->reflectedObject->hasMethod('getDefaultConfig'));
     $this->assertTrue($this->reflectedObject->hasProperty('ts'));
     $this->assertTrue($this->reflectedObject->hasProperty('shortcodes'));
     $this->assertTrue($this->reflectedObject->hasProperty('config'));
 }
 protected function getProperty($name)
 {
     if (!$this->target->hasProperty($name)) {
         $message = sprintf('Property not found on object %s.', get_class($this->origin));
         throw new OutOfBoundsException($message);
     }
     /** @var ReflectionProperty $property */
     $property = $this->target->getProperty($name);
     $property->setAccessible(true);
     return $property;
 }
 /**
  * Adds the name of the specified hook to $hooks using reflection.
  * @param $class_name
  */
 private function add_hook_reflect($class_name)
 {
     $reflector = new ReflectionClass($class_name);
     if (!$reflector->isAbstract() && $reflector->isSubclassOf("Hook") && $class_name !== "GenericHook" && $reflector->hasProperty("friendly_name")) {
         $instance = $reflector->newInstance();
         $name = $reflector->getProperty("friendly_name")->getValue($instance);
         $this->hooks[$name] = "";
         if ($this->get_config("Main", "web_hooks") && $reflector->hasProperty("web") && $reflector->getProperty("web")->getValue($instance)) {
             $this->web_hooks[$name] = "";
         }
     }
 }
 /**
  * @param $property_name
  * @param $name
  * @return \Symforce\CoreBundle\Annotation\SymforceAbstractAnnotation|array
  * @throws \Exception
  */
 public function getPropertyValue($property_name, $name, $fetch_values = false)
 {
     if (!$this->reflection->hasProperty($property_name)) {
         throw new \Exception(sprintf("class property(%s->%s) not exists in file: %s ", $this->name, $property_name, $this->reflection->getFileName()));
     }
     if (!isset($this->properties_annotations[$property_name][$name])) {
         throw new \Exception();
     }
     if ($fetch_values) {
         $this->properties_annotations[$property_name][$name]->values;
     }
     return $this->properties_annotations[$property_name][$name]->value;
 }
Example #9
0
 public function __construct($data = NULL)
 {
     if (!is_null($data) && !is_numeric($data) && !is_array($data) && !$data instanceof stdClass) {
         throw new ShopException('Invalid $data type');
     }
     if (is_array($data) || $data instanceof stdClass) {
         $this->loadFromArray((array) $data);
     }
     /**
      * Look for Item repository.
      * For IDE purposes like code completion $this->repo's type should be hinted in each Item the way I did in Cart.
      */
     $repoClass = $this->getRepo();
     $reflection = new ReflectionClass($repoClass);
     $repoClass = (string) $reflection->getName();
     $this->repo = $reflection->isInstantiable() ? new $repoClass() : null;
     /**
      * Look for srl field if it's not already set in class $meta
      */
     $reflection = new ReflectionClass($this);
     if ($srlField = $this->getMeta('srl')) {
         //if srl is given
         if (!$reflection->hasProperty($srlField)) {
             throw new ShopException("Srl field '{$srlField}' doesn't exist");
         }
     } elseif ($reflection->hasProperty('srl')) {
         $this->setMeta('srl', 'srl');
     } else {
         //else return the first _srl field
         foreach ($this as $field => $value) {
             if (substr($field, strlen($field) - 4, strlen($field)) === '_srl') {
                 $this->setMeta('srl', $field);
                 break;
             }
         }
         if (!$this->getMeta('srl')) {
             throw new ShopException('Couldn\'t identify the _srl column');
         }
     }
     //data can also be a serial
     if (is_numeric($data)) {
         if ($obj = $this->repo->get($data, "get%E", get_called_class())) {
             $this->copy($obj);
         } else {
             throw new ShopException("No such {$this->repo->entity} srl {$data}");
         }
     }
     if (is_null(self::$cache)) {
         self::$cache = new ShopCache();
     }
 }
Example #10
0
 public function __toString()
 {
     $object = new \ReflectionClass($this);
     // Get the name of the constant type
     $type = array_search($this->getType(), $object->getConstants());
     // SimpleToken
     if ($object->hasProperty('value')) {
         return sprintf('Token: %s Value: %s', $type, $this->getValue());
     } elseif ($object->hasProperty('name')) {
         return sprintf('Token: %s Namespace: %s Name: %s', $type, $this->getNamespace(), $this->getName());
     } else {
         return sprintf('Token: %s', $type);
     }
 }
Example #11
0
 /**
  * Casts objects to arrays and adds the dynamic property prefix.
  *
  * @param object           $obj       The object to cast
  * @param \ReflectionClass $reflector The class reflector to use for inspecting the object definition
  *
  * @return array The array-cast of the object, with prefixed dynamic properties
  */
 public static function castObject($obj, \ReflectionClass $reflector)
 {
     if ($reflector->hasMethod('__debugInfo')) {
         $a = $obj->__debugInfo();
     } elseif ($obj instanceof \Closure) {
         $a = array();
     } else {
         $a = (array) $obj;
     }
     if ($obj instanceof \__PHP_Incomplete_Class) {
         return $a;
     }
     if ($a) {
         $combine = false;
         $p = array_keys($a);
         foreach ($p as $i => $k) {
             if (isset($k[0]) && "" !== $k[0] && !$reflector->hasProperty($k)) {
                 $combine = true;
                 $p[$i] = self::PREFIX_DYNAMIC . $k;
             } elseif (isset($k[16]) && "" === $k[16] && 0 === strpos($k, "class@anonymous")) {
                 $combine = true;
                 $p[$i] = "" . $reflector->getParentClass() . '@anonymous' . strrchr($k, "");
             }
         }
         if ($combine) {
             $a = array_combine($p, $a);
         }
     }
     return $a;
 }
Example #12
0
 /**
  * Este escucha permite esteblecer el consecutivo de las entidades 
  * al momento de ser almacenadas en base de datos
  * @author Cesar Giraldo <*****@*****.**> 23/12/2015
  * @param LifecycleEventArgs $args
  */
 public function postPersist(LifecycleEventArgs $args)
 {
     $entity = $args->getEntity();
     $className = get_class($entity);
     $entityManager = $args->getEntityManager();
     $reflectedClass = new \ReflectionClass($className);
     if ($reflectedClass->hasProperty('consecutive')) {
         $consecutive = null;
         $enabledEntity = false;
         if ($entity instanceof Entity\Item) {
             $enabledEntity = true;
             //buscamos la cantidad de items que tiene creado un proyecto para asignar el consecutivo
             $project = $entity->getProject();
             $consecutive = $project->getLastItemConsecutive() + 1;
             $project->setLastItemConsecutive($consecutive);
             $entityManager->persist($project);
         } elseif ($entity instanceof Entity\Sprint) {
             $enabledEntity = true;
             //buscamos la cantidad de items que tiene creado un proyecto para asignar el consecutivo
             $project = $entity->getProject();
             $consecutive = $project->getLastSprintConsecutive() + 1;
             $project->setLastSprintConsecutive($consecutive);
             $entityManager->persist($project);
         }
         if ($enabledEntity) {
             if ($consecutive != null) {
                 $entity->setConsecutive($consecutive);
             } else {
                 $entity->setConsecutive(1);
             }
             $entityManager->flush();
         }
     }
 }
 public function setBriefProperty($object, $name, $value, $expectedClass = null)
 {
     $reflection = new \ReflectionClass($object);
     if (!$reflection->hasProperty($name)) {
         return false;
     }
     $property = $reflection->getProperty($name);
     $property->setAccessible(true);
     if ($value instanceof Resource) {
         $value = $value->getUri();
         $annotation = $this->annotationReader->getPropertyAnnotation($property, 'Soil\\CommentsDigestBundle\\Annotation\\Entity');
         if ($annotation) {
             $expectedClass = $annotation->value ?: true;
             var_dump($expectedClass);
             try {
                 $entity = $this->resolver->getEntityForURI($value, $expectedClass);
             } catch (\Exception $e) {
                 $entity = null;
                 echo "Problem with discovering" . PHP_EOL;
                 echo $e->getMessage() . PHP_EOL;
                 var_dump($value, $expectedClass);
                 echo PHP_EOL;
                 //FIXME: Add logging
             }
             if ($entity) {
                 $value = $entity;
             }
         }
     } elseif ($value instanceof Literal) {
         $value = $value->getValue();
     }
     $property->setValue($object, $value);
 }
Example #14
0
 /**
  * @param $tableField TableField
  * @param $value object
  * @param $propertyName string
  * @param $destination object
  * @return mixed|EntityProxy
  */
 private function setPropertyValue($tableField, $value, $propertyName, $destination)
 {
     if (!is_null($value)) {
         if ($tableField->isNumericType()) {
             settype($value, "float");
         } elseif ($tableField->isBoolType()) {
             settype($value, "boolean");
         } elseif ($tableField->isStringType()) {
             settype($value, "string");
         }
     }
     if ($fkConstraint = $tableField->getForeignKeyConstraint()) {
         if ($fkConstraint->isOneToMany()) {
             $referencedTableData = $fkConstraint->getForeignKeyField()->getTable();
             $entity = $referencedTableData->getEntityInstance();
             $value = new CollectionProxy($destination, $this->daoFactory->getDaoFromEntity($entity), $tableField);
         } else {
             $referencedTableData = $fkConstraint->getForeignKeyField()->getTable();
             $entity = $referencedTableData->getEntityInstance();
             $value = new EntityProxy($destination, $entity, $this->daoFactory->getDaoFromEntity($entity), $tableField);
         }
     }
     if ($this->reflectionEntityClass->hasProperty($propertyName)) {
         $property = $this->reflectionEntityClass->getProperty($propertyName);
         if (!$property->isPublic()) {
             $property->setAccessible(true);
             $property->setValue($destination, $value);
             $property->setAccessible(false);
         } else {
             $property->setValue($destination, $value);
         }
     } else {
         $destination->{$propertyName} = $value;
     }
 }
Example #15
0
 /**
  * {@inheritdoc}
  */
 public function process(ContainerBuilder $container)
 {
     foreach ($container->findTaggedServiceIds('mautic.model') as $id => $tags) {
         $definition = $container->findDefinition($id);
         $definition->addMethodCall('setEntityManager', [new Reference('doctrine.orm.entity_manager')]);
         $definition->addMethodCall('setSecurity', [new Reference('mautic.security')]);
         $definition->addMethodCall('setDispatcher', [new Reference('event_dispatcher')]);
         $definition->addMethodCall('setTranslator', [new Reference('translator')]);
         $definition->addMethodCall('setUserHelper', [new Reference('mautic.helper.user')]);
         $modelClass = $definition->getClass();
         $reflected = new \ReflectionClass($modelClass);
         if ($reflected->hasMethod('setRouter')) {
             $definition->addMethodCall('setRouter', [new Reference('router')]);
         }
         if ($reflected->hasMethod('setLogger')) {
             $definition->addMethodCall('setLogger', [new Reference('monolog.logger.mautic')]);
         }
         if ($reflected->hasMethod('setSession')) {
             $definition->addMethodCall('setSession', [new Reference('session')]);
         }
         // Temporary, for development purposes
         if ($reflected->hasProperty('factory')) {
             $definition->addMethodCall('setFactory', [new Reference('mautic.factory')]);
         }
     }
 }
 public function enterNode(\PHPParser_Node $node)
 {
     if ($node instanceof \PHPParser_Node_Stmt_Namespace) {
         $this->namespace = implode('\\', $node->name->parts);
         return;
     }
     if (!$node instanceof \PHPParser_Node_Stmt_Class) {
         return;
     }
     $name = '' === $this->namespace ? $node->name : $this->namespace . '\\' . $node->name;
     if (!class_exists($name)) {
         return;
     }
     if (!is_a($name, 'Symfony\\Component\\Validator\\Constraint', true)) {
         return;
     }
     $constraint = $name::create($this->app);
     $ref = new \ReflectionClass($name);
     foreach ($this->messageProperties as $prop) {
         if ($ref->hasProperty($prop)) {
             $message = new Message($constraint->{$prop}, 'validators');
             $this->catalogue->add($message);
         }
     }
 }
 private function _init(\ReflectionClass $rc, $property_name, SymforceAbstractAnnotation $annotation)
 {
     $this->class_reflection = $rc;
     $this->property_name = $property_name;
     $this->annotation_name = $annotation::SYMFORCE_ANNOTATION_NAME;
     $value_property_name = $annotation::SYMFORCE_ANNOTATION_VALUE_AS_PROPERTY;
     if ($value_property_name) {
         $_rc = new \ReflectionClass($annotation);
         if (!$_rc->hasProperty($value_property_name)) {
             throw new \Exception();
         }
         $value_property_as_key = $annotation::SYMFORCE_ANNOTATION_VALUE_AS_KEY;
         $value_property_not_null = $annotation::SYMFORCE_ANNOTATION_VALUE_NOT_NULL;
         $value_property_value = $_rc->getProperty($value_property_name)->getValue($annotation);
         if (!$value_property_value) {
             if ($value_property_not_null) {
                 throw new \Exception(sprintf("%s annotation.%s can not be null", $this->getAnnotationResourceDescription(), $value_property_name));
             }
             $this->value = $annotation;
         } else {
             if ($value_property_as_key) {
                 $this->values[$value_property_value] = $annotation;
             } else {
                 $this->value = $annotation;
             }
         }
     } else {
         $this->value = $annotation;
     }
 }
Example #18
0
 public static function toObject()
 {
     $args = func_get_args();
     if (count($args) >= 2) {
         $className = '\\' . str_replace('.', '\\', $args[0]);
         $refClass = new \ReflectionClass($className);
         $toObjInstance = $refClass->newInstance();
         unset($args[0]);
         foreach ($args as $arg) {
             if (is_object($arg)) {
                 $arg = Object::getProperties($arg);
             }
             if (is_array($arg)) {
                 foreach ($arg as $propertyName => $propertyValue) {
                     if ($refClass->hasProperty($propertyName)) {
                         $property = $refClass->getProperty($propertyName);
                         $property->setAccessible(true);
                         $property->setValue($toObjInstance, $propertyValue);
                     }
                 }
             }
         }
         return $toObjInstance;
     }
 }
Example #19
0
 /**
  * Initialize preferences
  *
  * @access	public
  * @param	array
  * @return	void
  */
 public function initialize(array $config = array(), $reset = TRUE)
 {
     $reflection = new ReflectionClass($this);
     if ($reset === TRUE) {
         $defaults = $reflection->getDefaultProperties();
         foreach (array_keys($defaults) as $key) {
             if ($key[0] === '_') {
                 continue;
             }
             if (isset($config[$key])) {
                 if ($reflection->hasMethod('set_' . $key)) {
                     $this->{'set_' . $key}($config[$key]);
                 } else {
                     $this->{$key} = $config[$key];
                 }
             } else {
                 $this->{$key} = $defaults[$key];
             }
         }
     } else {
         foreach ($config as $key => &$value) {
             if ($key[0] !== '_' && $reflection->hasProperty($key)) {
                 if ($reflection->hasMethod('set_' . $key)) {
                     $this->{'set_' . $key}($value);
                 } else {
                     $this->{$key} = $value;
                 }
             }
         }
     }
     // if a file_name was provided in the config, use it instead of the user input
     // supplied file name for all uploads until initialized again
     $this->_file_name_override = $this->file_name;
     return $this;
 }
Example #20
0
 public static function castArrayObject(\ArrayObject $c, array $a, Stub $stub, $isNested)
 {
     $class = $stub->class;
     $flags = $c->getFlags();
     $b = array("~flag::STD_PROP_LIST" => (bool) ($flags & \ArrayObject::STD_PROP_LIST), "~flag::ARRAY_AS_PROPS" => (bool) ($flags & \ArrayObject::ARRAY_AS_PROPS), "~iteratorClass" => $c->getIteratorClass(), "~storage" => $c->getArrayCopy());
     if ($class === 'ArrayObject') {
         $a = $b;
     } else {
         if (!($flags & \ArrayObject::STD_PROP_LIST)) {
             $c->setFlags(\ArrayObject::STD_PROP_LIST);
             if ($a = (array) $c) {
                 $class = new \ReflectionClass($class);
                 foreach ($a as $k => $p) {
                     if (!isset($k[0]) || "" !== $k[0] && !$class->hasProperty($k)) {
                         unset($a[$k]);
                         $a["+" . $k] = $p;
                     }
                 }
             }
             $c->setFlags($flags);
         }
         $a += $b;
     }
     return $a;
 }
Example #21
0
 /**
  * Creates or gets an instance for class with class
  *
  * *Additional args* can be passed to this method. In this case they will be used to instantiate
  * the new class. If new class is instance of {@link AbsPluginSingleton} or {@link AbsCoreSingleton}
  * then additional args will be discarded. If class to be instantiated has $plugin property then the plugin
  * instance is added to the head of additional args. In that case the class constructor should have `Plugin $plugin`
  * argument first.
  *
  * **IMPORTANT** If class is instance of {@link AbsPluginSingleton} or {@link AbsCoreSingleton} then
  * {@link AbsPluginSingleton::getInstance()} or {@link AbsCoreSingleton::getInstance()}
  * is used. In that case any additional args will be discarded. If this is not the case then a new
  * instance of class is returned.
  *
  * @param string $className baseNamespace must be omitted. eg. `$className = 'MyBaseNamespaceChildren\MyClass'
  *
  * @return object An instance of [baseNamespace]\$className
  * @throws Exception If class not found or isn't instantiable or is plugin class has same name as one in core and
  *                   doesn't extend this core class.
  * @author Panagiotis Vagenas <*****@*****.**>
  * @since  0.0.2
  */
 public function createOrGet($className)
 {
     if ($this->existsInPlugin($className)) {
         if ($this->coreClassExists($className) && !$this->isCoreExtension($className)) {
             throw new Exception('Classes that have core name should ALWAYS extend core classes. Class name: ' . $className);
         }
         $class = $this->getPluginClassName($className);
     } elseif ($this->coreClassExists($className)) {
         $class = $this->getCoreClassName($className);
     } else {
         throw new Exception('Class ' . $className . ' doesn\'t seem to exists!');
     }
     $args = func_get_args();
     array_shift($args);
     $reflection = new \ReflectionClass($class);
     if (!$reflection || !($reflection->isSubclassOf($this->getCoreClassNameFromBase('Abs\\AbsPluginSingleton')) || $reflection->isSubclassOf($this->getCoreClassNameFromBase('Abs\\AbsCoreSingleton'))) && !$reflection->isInstantiable()) {
         throw new Exception('Trying to instantiate non-instantiable class ' . $class);
     }
     if ($reflection->isSubclassOf($this->getCoreClassNameFromBase('Abs\\AbsPluginSingleton'))) {
         /* @var AbsPluginSingleton $class */
         $instance = $class::getInstance($this->plugin);
     } elseif ($reflection->isSubclassOf($this->getCoreClassNameFromBase('Abs\\AbsCoreSingleton'))) {
         /* @var AbsCoreSingleton $class */
         $instance = $class::getInstance();
     } else {
         if ($reflection->hasProperty('plugin') && (empty($args) || isset($args[0]) && !$args[0] instanceof Plugin)) {
             array_unshift($args, $this->plugin);
         }
         $instance = $reflection->newInstanceArgs($args);
     }
     return $instance;
 }
Example #22
0
 public function getPropertyTwigValue($property, $object)
 {
     if (isset($this->_property_twig_value[$property])) {
         $access = $this->_property_twig_value[$property];
     } else {
         $access = null;
         $get = 'get' . $this->camelize($property);
         if ($this->reflection->hasMethod($get)) {
             $method = $this->reflection->getMethod($get);
             if ($method->isPublic() && !$method->isStatic() && !count($method->getParameters())) {
                 $access = '.' . $get . '()';
             }
         } else {
             if ($this->reflection->hasProperty($property)) {
                 $prop = $this->reflection->getProperty($property);
                 if ($prop->isPublic()) {
                     $access = '.' . $property;
                 } else {
                     $access = false;
                 }
             } else {
                 throw new \Exception(sprintf("admin(%s) do not has property(%s->%s), and do not has methed(%s)", $this->name, $this->class_name, $property, $get));
             }
         }
         $this->_property_twig_value[$property] = $access;
     }
     if (false === $access) {
         return sprintf('attribute(%s, "%s")', $object, $property);
     }
     return sprintf('%s%s', $object, $access);
 }
Example #23
0
 public function __construct($id = null, $name = null, $args = null)
 {
     settype($id, 'int');
     settype($name, 'string');
     settype($args, 'array');
     if ($id > 0) {
         $this->load($id);
     } elseif (strlen($name) > 0) {
         if (!class_exists($name)) {
             throw new Exception("Class {$name} not exists");
         }
         // if ( sizeof($args) > 0 )
         // {
         $reflection = new ReflectionClass($name);
         if (!$reflection->hasProperty('jObjects')) {
             throw new Exception("Class not supported by jObjects");
         }
         $this->_instance = call_user_func_array(array(&$reflection, 'newInstance'), $args);
         // }
         // else
         //     $this->_instance = new $name();
         $this->save();
     } else {
         throw new Exception('Bad parameters');
     }
 }
 /**
  * Map collection by key. For objects, return the property, use
  * get method or is method, if avaliable.
  *
  * @param  array                     $input Array of arrays or objects.
  * @param  string                    $key   Key to map by.
  * @throws \InvalidArgumentException If array item is not an array or object.
  * @throws \LogicException           If array item could not be mapped by given key.
  * @return array                     Mapped array.
  */
 public function mapBy(array $input, $key)
 {
     return array_map(function ($item) use($key) {
         if (is_array($item)) {
             if (!array_key_exists($key, $item)) {
                 throw new \LogicException("Could not map item by key \"{$key}\". Array key does not exist.");
             }
             return $item[$key];
         }
         if (!is_object($item)) {
             throw new \InvalidArgumentException("Item must be an array or object.");
         }
         $ref = new \ReflectionClass($item);
         if ($ref->hasProperty($key) && $ref->getProperty($key)->isPublic()) {
             return $item->{$key};
         }
         if ($ref->hasMethod($key) && !$ref->getMethod($key)->isPrivate()) {
             return $item->{$key}();
         }
         $get = 'get' . ucfirst($key);
         if ($ref->hasMethod($get) && !$ref->getMethod($get)->isPrivate()) {
             return $item->{$get}();
         }
         $is = 'is' . ucfirst($key);
         if ($ref->hasMethod($is) && !$ref->getMethod($is)->isPrivate()) {
             return $item->{$is}();
         }
         throw new \LogicException("Could not map item by key \"{$key}\". Cannot access the property directly or through getter/is method.");
     }, $input);
 }
 public function testClassBrowserResult()
 {
     $class = new \ReflectionClass('WhichBrowser\\Model\\Browser');
     $this->assertTrue($class->hasMethod('getName'), 'method getName() does not exist anymore');
     $this->assertTrue($class->hasMethod('getVersion'), 'method getVersion() does not exist anymore');
     $this->assertTrue($class->hasProperty('using'), 'property using does not exist anymore');
 }
 /**
  * @param array $mapping
  */
 private function initReflField(array $mapping)
 {
     if ($this->reflClass->hasProperty($mapping['fieldName'])) {
         $reflProp = $this->reflClass->getProperty($mapping['fieldName']);
         $reflProp->setAccessible(true);
         $this->reflFields[$mapping['fieldName']] = $reflProp;
     }
 }
Example #27
0
 /**
  * @param string $name
  * @param string $type
  * @param array  $options
  *
  * @return $this
  */
 public function add($name, $type = 'string', array $options = array())
 {
     $getMethod = 'get' . ucfirst($name);
     $isMethod = 'is' . ucfirst($name);
     $isAccessible = false;
     if ($this->reflectionClass->hasProperty($name) && $this->reflectionClass->getProperty($name)->isPublic() || $this->reflectionClass->hasMethod($getMethod) && $this->reflectionClass->getMethod($getMethod)->isPublic() || $this->reflectionClass->hasMethod($isMethod) && $this->reflectionClass->getMethod($isMethod)->isPublic()) {
         $isAccessible = true;
     }
     if (!$isAccessible) {
         throw new \InvalidArgumentException(sprintf('There is no public property, get or is method for: %s!', $name));
     }
     if (!$type instanceof TypeInterface) {
         $type = $this->getType($type);
     }
     $this->fields[] = new Field($name, $type->getName(), $type->getTemplate(), $options);
     return $this;
 }
 /**
  * Magic function which handles the get properties accessibility.
  * @param string $propertyName The property name.
  */
 public function __get($propertyName)
 {
     $class = new \ReflectionClass($this);
     if ($class->hasProperty($propertyName)) {
         $property = $class->getProperty($propertyName);
         $property->setAccessible(true);
         return $property->getValue($this);
     } else {
         if ($class->hasProperty('_' . $propertyName)) {
             $property = $class->getProperty('_' . $propertyName);
             $property->setAccessible(true);
             return $property->getValue($this);
         }
     }
     // EXCEPTION!!
     return null;
 }
 function it_throws_exception_when_setProducts_method_does_not_exist(ManagerRegistry $registry, EntityManager $em, LifecycleEventArgs $args, ClassMetadata $metadata, \ReflectionClass $reflClass, LifecycleEventArgs $args, InvalidProductsAware $entity)
 {
     $args->getEntity()->willReturn($entity);
     $args->getEntityManager()->willReturn($em);
     $em->getClassMetadata(Argument::type('string'))->willReturn($metadata);
     $metadata->reflClass = $reflClass;
     $reflClass->hasProperty('products')->willReturn(false);
     $this->shouldThrow('\\LogicException')->duringPostLoad($args);
 }
Example #30
0
 /**
  * @param $target
  * @param $source
  * @param $propertyName
  * @throws InvalidArgumentException
  * @throws NotExistingPropertyException
  */
 public function cloneProperty($target, $source, $propertyName)
 {
     $this->validaObjects($target, $source);
     $reflection = new \ReflectionClass($target);
     if (!$reflection->hasProperty($propertyName)) {
         throw new NotExistingPropertyException();
     }
     $this->propertyAccessor->setValue($target, $propertyName, $this->propertyAccessor->getValue($source, $propertyName));
 }