protected function startReflection() { $this->class = get_class($this); $refClass = new ReflectionClass($this->class); $this->properties = $refClass->getProperties(); //set table name $tableNameArr = array(); preg_match("/(@Tablename )(.*)/", $refClass->getDocComment(), $tableNameArr); if (isset($tableNameArr[0])) { $this->table = $tableNameArr[2]; } else { $this->table = strtolower($this->class); } //set columns $cont = 0; foreach ($this->properties as $prop) { if ($prop->class != "DAO") { $columnNamesArr = array(); $refProp = new ReflectionProperty($this->class, $prop->name); preg_match("/(@Columnname )(.*)/", $refProp->getDocComment(), $columnNamesArr); preg_match("/(@Columntype )(.*)/", $refProp->getDocComment(), $columnTypesArr); $this->columns[$cont]['name'] = $prop->name; if (isset($columnNamesArr[0])) { $this->columns[$cont]['column'] = $columnNamesArr[2]; } else { $this->columns[$cont]['column'] = strtolower($prop->name); } $this->columns[$cont]['type'] = isset($columnTypesArr[2]) ? $columnTypesArr[2] : 'string'; $cont++; } } //reflection object $this->refObj = new ReflectionObject($this); }
/** * @param $pattern * @return null|string */ private function match($pattern) { $matches = array(); $found = preg_match($pattern, $this->property->getDocComment(), $matches); if (!$found) { return null; } return $matches[1]; }
public function __construct(\ReflectionClass $reflectionClass, \ReflectionProperty $reflectionProperty) { $reflectionProperty->setAccessible(true); if (strpos($reflectionProperty->getDocComment(), "@skipSerialization") !== false) { $this->isSkipped = true; } if (strpos($reflectionProperty->getDocComment(), "@var") === false) { throw new PropertyTypeWasNotDefined($reflectionClass->getName(), $reflectionProperty->getName()); } if (preg_match('/@var\\s+([^\\s]+)/', $reflectionProperty->getDocComment(), $matches)) { list(, $type) = $matches; $types = explode("|", $type); if (!empty($types)) { foreach ($types as $type) { if ($pos = strpos($type, '[]')) { $this->isArray = true; $type = substr($type, 0, $pos); } if (class_exists($type)) { // Object $this->types[] = $type; $typeReflectionClass = new \ReflectionClass($type); if (!$typeReflectionClass->isInterface() && !$typeReflectionClass->isAbstract()) { $this->isObject = $type; } } else { $typeCheck = $reflectionClass->getNamespaceName() . '\\' . $type; if (class_exists($typeCheck)) { // Object $this->types[] = $typeCheck; $typeReflectionClass = new \ReflectionClass($typeCheck); if (!$typeReflectionClass->isInterface() && !$typeReflectionClass->isAbstract()) { $this->isObject = $typeCheck; } } else { $aliases = $this->getAliases($reflectionClass->getFileName()); if (array_key_exists($type, $aliases) && class_exists($aliases[$type])) { $type = $aliases[$type]; // Object $this->types[] = $type; $typeReflectionClass = new \ReflectionClass($type); if (!$typeReflectionClass->isInterface() && !$typeReflectionClass->isAbstract()) { $this->isObject = $type; } } else { $this->types[] = $type = null; } } } } array_unique($this->types); } } $this->reflectionClass = $reflectionClass; $this->reflectionProperty = $reflectionProperty; }
/** * @return self */ public static function from(\ReflectionProperty $from) { $prop = new static($from->getName()); $defaults = $from->getDeclaringClass()->getDefaultProperties(); $prop->value = isset($defaults[$prop->name]) ? $defaults[$prop->name] : NULL; $prop->static = $from->isStatic(); $prop->visibility = $from->isPrivate() ? 'private' : ($from->isProtected() ? 'protected' : 'public'); $prop->comment = $from->getDocComment() ? preg_replace('#^\\s*\\* ?#m', '', trim($from->getDocComment(), "/* \r\n\t")) : NULL; return $prop; }
/** * Generic class property resolver. * * @param \ReflectionProperty $property * @param ClassMetadata $classMetadata * * @return PropertyMetadata Resolved property metadata */ protected function resolvePropertyMetadata(\ReflectionProperty $property, ClassMetadata $classMetadata) : PropertyMetadata { // Create method metadata instance $propertyMetadata = $classMetadata->propertiesMetadata[$property->getName()] ?? new PropertyMetadata($classMetadata); $propertyMetadata->name = $property->getName(); $propertyMetadata->modifiers = $property->getModifiers(); $propertyMetadata->isPublic = $property->isPublic(); $propertyMetadata->typeHint = $this->getCommentTypeHint(is_string($property->getDocComment()) ? $property->getDocComment() : ''); // Store property metadata to class metadata return $classMetadata->propertiesMetadata[$propertyMetadata->name] = $propertyMetadata; }
public function __construct(\ReflectionProperty $property, array $classConfig, \rg\injektor\Configuration $config, \rg\injektor\DependencyInjectionContainer $dic) { $this->property = $property; $this->classConfig = $classConfig; $this->config = $config; $this->dic = $dic; $this->name = $property->name; $this->docComment = $this->property->getDocComment(); $this->additionalArguments = $this->dic->getParamsFromPropertyTypeHint($this->property, 'var'); $this->analyze(); }
/** * Parse the docblock of the property to get the class of the var annotation. * * @param \ReflectionProperty $property * * @throws AnnotationException Non exists class. * * @return null|ObjectDefinition */ public function getPropertyClass(\ReflectionProperty $property) { $propertyComment = $property->getDocComment(); if (!preg_match('/@var\\s+([^\\s\\(\\*\\/]+)/', $propertyComment, $matches)) { return; } $className = end($matches); if (!is_string($className) || in_array($className, static::$ignoredTypes)) { return; } $classWithNamespace = $className; if ($this->namespaceExists($classWithNamespace) === false) { $classWithNamespace = $this->namespace . '\\' . $className; } if (!$this->classExists($classWithNamespace)) { $declaringClass = $property->getDeclaringClass(); throw new AnnotationException(sprintf('The @var annotation on %s::%s contains a non existent class "%s"', $declaringClass->name, $property->getName(), $className)); } $createNewObject = function ($propertyComment, $className, $classWithNamespace) { $classParameters = $this->propertyClassParameters($propertyComment, $className); if (is_array($classParameters)) { $values = []; foreach ($classParameters as $value) { $values[] = static::parseValue($value); } $object = new ObjectDefinition($classWithNamespace, $className); $object->setConstructorInjection($values); return $object; } return new $classWithNamespace(); }; return $createNewObject($propertyComment, $className, $classWithNamespace); }
/** * <p> * Polymorphic method that allows you to retreive both Object, Attributes and Methods documentation * from the current object. * </p> * * @param String $method */ public function getDocumentation($target = NULL, $type = self::OBJECT) { if ($target == NULL && $type != self::OBJECT) { return FALSE; } switch ($type) { case self::OBJECT: $target = $target == NULL ? $this->obj : $target; $reflection = new ReflectionClass($target); break; case self::METHOD: $reflection = new ReflectionMethod($this->obj, $target); break; case self::ATTR: $reflection = new ReflectionProperty($this->obj, $target); break; default: return FALSE; break; } if (is_object($target)) { $target = get_class($target); } return $this->cacheComment[@get_class($this->obj)][$target] = $reflection->getDocComment(); }
protected function startReflection() { $this->class = get_class($this); $refClass = new ReflectionClass($this->class); $this->properties = $refClass->getProperties(); //set table name $tableNameArr = array(); preg_match("/(@Tablename )(.*)/", $refClass->getDocComment(), $tableNameArr); if (isset($tableNameArr[0])) { $this->table = $tableNameArr[2]; } else { $this->table = strtolower($this->class); } $this->getTableRows(); //set columns $cont = 0; foreach ($this->properties as $k => $prop) { if ($prop->class != "DAO") { $columnNamesArr = array(); $refProp = new ReflectionProperty($this->class, $prop->name); preg_match("/(@Columnname )(.*)/", $refProp->getDocComment(), $columnNamesArr); foreach ($this->columns as $id => $column) { if ($column['name'] == $prop->name || isset($columnNamesArr[0]) && $column['name'] == $columnNamesArr[2]) { $this->fieldsMap[$prop->name] = $id; } } $cont++; } else { unset($this->properties[$k]); } } //reflection object $this->refObj = new ReflectionObject($this); }
private function parseAttribute($class, $attribute) { $attr = new ReflectionProperty($class, $attribute); $annotations = array('validate' => $attr->isProtected(), 'mandatory' => true); $comment = $attr->getDocComment(); if (!$comment) { return $annotations; } if (!preg_match_all('/\\s*\\* @(\\w+) ([^\\n\\r]*)/', $comment, $matches)) { return $annotations; } foreach ($matches[1] as $index => $match) { $value = $matches[2][$index]; switch ($value) { case 'false': $value = false; break; case 'true': $value = true; break; } $annotations[$match] = $value; } return $annotations; }
private function getTypeOfProperty(\ReflectionProperty $prop) { if (preg_match('/^[\\s\\/*]*@var\\s+(\\S+)/m', $prop->getDocComment(), $matches)) { return $this->getFullNameOfType($matches[1], $prop->getDeclaringClass()); } return; }
/** * Method to validate the value object with the madatory fields * Uses the reflections to read the annotated objects * and set error message based on the text */ function validate() { $invalidProperties = array(); foreach (array_keys(get_class_vars(get_class($this))) as $key) { $value = $this->{$key}; $ref = new ReflectionProperty(get_class($this), $key); $docTagValue = $ref->getDocComment(); if (strpos($docTagValue, 'mandatory') != false) { if (!$this->checkIfNull($value, $key)) { array_push($invalidProperties, $this->getMessage($docTagValue, $key)); } } } print_r($this->containsDynamicField); if ($this->containsDynamicField) { foreach ($this->dynamicFields as $key) { $value = $this->{$key}; if (!$this->checkIfNull($value, $key)) { $messageValue = $this->dynamicFieldsValidation[$key]; if (!isset($messageValue) || $messageValue == null) { $messageValue = "Enter Value for " . $key; } array_push($invalidProperties, $messageValue); } } } return $invalidProperties; }
/** * @param ReflectionProperty * @param array (string => string) * @param string * @return string */ public function getNativePropertyType(ReflectionProperty $prop, &$defaults, &$type) { $name = $prop->getName(); if ($doc = trim($prop->getDocComment(), " \t\r\n*/")) { if (preg_match('/@var[ \\t]+([a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*)\\s*(:?\\[[\\s0-9]*\\]|)/', $doc, $m)) { if ($m[2]) { $type = 'arr'; } else { $type = substr(strtolower($m[1]), 0, 3); if ($type == 'mix') { $type = 'str'; } elseif (!in_array($type, self::$phpTypes)) { $type = 'obj'; } } } } if (!$type) { $type = substr(gettype(self::referenceObj($prop->getDeclaringClass()->getName())->{$name}), 0, 3); } $nativeType = $this->nativeTypes[$type == 'str' ? strlen('' . $defaults[$name]) > 255 ? 'tex' : 'str' : $type]; if (!$nativeType) { throw new IllegalTypeException('Unstorable type: ' . $type . ' for property: ' . $name); } return $nativeType; }
public function __construct($class, $property) { $property = new ReflectionProperty($class, $property); list($description, $tags) = Kodoc::parse($property->getDocComment()); $this->description = $description; if ($modifiers = $property->getModifiers()) { $this->modifiers = '<small>' . implode(' ', Reflection::getModifierNames($modifiers)) . '</small> '; } if (isset($tags['var'])) { if (preg_match('/^(\\S*)(?:\\s*(.+?))?$/', $tags['var'][0], $matches)) { $this->type = $matches[1]; if (isset($matches[2])) { $this->description = Markdown($matches[2]); } } } $this->property = $property; // Show the value of static properties, but only if they are public or we are php 5.3 or higher and can force them to be accessible if ($property->isStatic() and ($property->isPublic() or version_compare(PHP_VERSION, '5.3', '>='))) { // Force the property to be accessible if (version_compare(PHP_VERSION, '5.3', '>=')) { $property->setAccessible(TRUE); } // Don't debug the entire object, just say what kind of object it is if (is_object($property->getValue($class))) { $this->value = '<pre>object ' . get_class($property->getValue($class)) . '()</pre>'; } else { $this->value = Kohana::debug($property->getValue($class)); } } }
public function __construct(\ReflectionProperty $property) { $this->_property = $property; $comment = $property->getDocComment(); $comment = new DocBloc($comment); $this->_annotations = $comment->getAnnotations(); }
public function __construct() { $arguments = func_get_args(); $count = count($arguments); // get reflection from class or class/method // (depends on constructor arguments) if ($count === 0) { throw new \Exception("No zero argument constructor allowed"); } else { if ($count === 1) { $reflection = new \ReflectionClass($arguments[0]); } else { $type = $count === 3 ? $arguments[2] : "method"; if ($type === "method") { $reflection = new \ReflectionMethod($arguments[0], $arguments[1]); } else { if ($type === "property") { $reflection = new \ReflectionProperty($arguments[0], $arguments[1]); } } } } $this->rawDocBlock = $reflection->getDocComment(); $this->parameters = array(); }
public function __construct($class, $property, $default = null) { $property = new \ReflectionProperty($class, $property); list($description, $tags) = $this->userguide->parse($property->getDocComment()); $this->description = $description; if ($modifiers = $property->getModifiers()) { $this->modifiers = '<small>' . implode(' ', \Reflection::getModifierNames($modifiers)) . '</small> '; } if (isset($tags['var'])) { if (preg_match('/^(\\S*)(?:\\s*(.+?))?$/s', $tags['var'][0], $matches)) { $this->type = $matches[1]; if (isset($matches[2])) { $this->description = $this->markdown->transform($matches[2]); } } } $this->property = $property; // Show the value of static properties, but only if they are public or we are php 5.3 or // higher and can force them to be accessible if ($property->isStatic()) { $property->setAccessible(true); // Don't debug the entire object, just say what kind of object it is if (is_object($property->getValue($class))) { $this->value = '<pre>object ' . get_class($property->getValue($class)) . '()</pre>'; } else { $this->value = Debug::vars($property->getValue($class)); } } // Store the defult property $this->default = Debug::vars($default); }
protected function get_vars() { $model = get_called_class(); $params = get_class_vars($model); $vars = array(); $vars['tablename'] = $this->table_name(); foreach ($params as $k => $e) { $ft = new ReflectionProperty($model, $k); $comments = $ft->getDocComment(); $dfd = explode("\n", str_replace("\r", "", $comments)); $properties = array(); foreach ($dfd as $m) { $props = explode("@", $m); if (count($props) > 1) { $data = explode(" ", $props[1]); if (!isset($properties[$data[0]]) && isset($data[1])) { $properties[$data[0]] = $data[1]; } elseif (!isset($properties[$data[0]])) { $properties["properties"][] = $data[0]; } } } if (!empty($properties)) { $vars['fields'][] = $properties; } } return $vars; }
/** * returns null if there is no result from the parser * * @param \ReflectionProperty $reflectionParameter * * @return array */ public function make(\ReflectionProperty $reflectionParameter) { if (!$this->parser) { throw new \RuntimeException("Missing the parser Parser!"); } $result = $this->parser->parse($reflectionParameter->getDocComment()); if (!$result) { return []; } $validatorSet = []; $this->missingValidators = []; foreach ($result as $validatorToken) { // check if the annotation is with the full namespace already otherwise put it relative $className = $this->namespaceTransformer->transform($this->classNameTransformer->transform($validatorToken[AnnotationValidatorParser::INDEX_INTERFACE]), [AnnotationValidatorPrependNameSpace::NAMESPACE_OPTION_INDEX => __NAMESPACE__]); if (class_exists($className, true)) { // keep the validators in the runtime -> they are stateless and can be used as a reference if (empty($this->validatorTemplates[$className])) { $this->validatorTemplates[$className] = new $className(); } $validatorSet[] = [self::INDEX_RESULT => null, AnnotationValidatorParser::INDEX_MANDATORY => $validatorToken[AnnotationValidatorParser::INDEX_MANDATORY], AnnotationValidatorParser::INDEX_OPERATOR => $validatorToken[AnnotationValidatorParser::INDEX_OPERATOR], AnnotationValidatorParser::INDEX_INTERFACE => $this->validatorTemplates[$className], AnnotationValidatorParser::INDEX_EXPECTED => $validatorToken[AnnotationValidatorParser::INDEX_EXPECTED]]; } else { $this->missingValidators[] = $className; } } if ($this->missingValidators) { throw new \RuntimeException("There is one or more Validators Missing: " . implode(',', $this->missingValidators)); } return $validatorSet; }
/** * Initialize list of scalar properties by response * * @param \SimpleXMLElement $apiResponse * @param array $properties * @throws \Exception */ protected function _initScalarProperties($apiResponse, array $properties) { foreach ($properties as $property) { if (is_array($property)) { $classPropertyName = current($property); $value = $apiResponse->{key($property)}; } else { $classPropertyName = $this->_underToCamel(str_replace('-', '_', $property)); $value = $apiResponse->{$property}; } $reflectionProperty = new \ReflectionProperty($this, $classPropertyName); $docBlock = $reflectionProperty->getDocComment(); $propertyType = preg_replace('/^.+ @var ([a-z]+) .+$/', '\\1', $docBlock); if ('string' == $propertyType) { $value = (string) $value; } else { if ('integer' == $propertyType) { $value = (int) $value; } else { if ('boolean' == $propertyType) { $value = in_array((string) $value, ['true', 'on', 'enabled']); } else { throw new \Exception("Unknown property type '{$propertyType}'."); } } } $this->{$classPropertyName} = $value; } }
private function parse_doc_comment(\ReflectionProperty $property) { $doc_comment = $property->getDocComment(); $doc_comment = trim(preg_replace('/\\r?\\n *\\* *\\//', '', $doc_comment)); $comments = []; preg_match_all('/@([a-z]+)\\s+(.*?)\\s*(?=$|@[a-z]+\\s)/s', $doc_comment, $comments); return array_combine($comments[1], $comments[2]); }
public function getPropertyComment($property) { $propertyReflection = new \ReflectionProperty($this->obj, $property); if ($comment = $propertyReflection->getDocComment()) { return $this->cleanDocComment($comment); } return null; }
/** * Reads a property comment * * @param string $property Property name * @return string Property comment * @throws \LogicException When the property isn't found */ protected function sgComment($property) { try { $reflection = new \ReflectionProperty(__CLASS__, $property); return $reflection->getDocComment(); } catch (\ReflectionException $e) { throw new \LogicException('Property does not exist', 0, $e); } }
/** * Formatar float para o número de casas decimais correto. * @param $nome * @param $valor * @return string */ protected function formatar($nome, $valor) { $ref = new \ReflectionProperty(get_class($this), $nome); $factory = DocBlockFactory::createInstance(); $info = $factory->create($ref->getDocComment()); // Pegar o tipo da variavel $tipo = $info->getTagsByName('var'); $tipo = count($tipo) == 0 ? 'string' : $tipo[0]->getType(); $tipo = strtolower($tipo); switch ($tipo) { case 'string': case 'string|null': case '\\string': case '\\string|null': $valor = str_replace(['@'], ['#1#'], utf8_encode($valor)); // Ignorar alguns caracteres no ascii $valor = Str::ascii($valor); $valor = str_replace(['&'], ['e'], $valor); $valor = str_replace(['#1#'], ['@'], $valor); // Retornar caracteres ignorados $valor = Str::upper($valor); $valor = trim($valor); // Max $max = $info->getTagsByName('max'); if (count($max) > 0) { $max = intval($max[0]->getDescription()->render()); $valor = trim(substr($valor, 0, $max)); } return $valor; case 'float|null': case 'float': $dec = $info->getTagsByName('dec'); if (count($dec) == 0) { return $valor; } // Valor do @dec $dec = $dec[0]->getDescription()->render(); return number_format($valor, $dec, '.', ''); case 'datetime': case '\\datetime': case '\\datetime|null': case 'date': case 'date|null': case '\\date': case '\\date|null': if (is_int($valor)) { $valor = Carbon::createFromTimestamp($valor); } if (is_string($valor)) { return $valor; } $format = in_array($tipo, ['date', 'date|null', '\\date', '\\date|null']) ? 'Y-m-d' : Carbon::ATOM; return $valor->format($format); default: return $valor; } }
public function getPropertyAnnotations(\ReflectionProperty $prop) { $annotations = $this->getAnnotations($prop->getDocComment(), "property: {$prop->getDeclaringClass()->name}::{$prop->name}"); $varAnnotations = $annotations['vars']; return array_reduce(array_keys($varAnnotations), function (array &$tmp, $i) use($prop, $varAnnotations) { $a = $varAnnotations[$i]; $a->name = $prop->name; return $tmp + [$i => $a]; }, []); }
/** * Returns the PHPDoc comment of the property. * * @return string PHPDoc comment * @since PHP 5.1.0 */ public function getDocComment() { if ($this->reflectionSource instanceof ReflectionProperty) { // query external reflection object $comment = $this->reflectionSource->getDocComment(); } else { $comment = parent::getDocComment(); } return $comment; }
public function getDocComment($onlytext = FALSE) { $doc = parent::getDocComment(); if ($onlytext) { $doc = s($doc)->preg_replace("/(?<=[\r\n])[\\s]*\\*(\\ )?(?![\\/])/", ""); $doc = s($doc)->preg_replace("/^[\\s]*\\/\\*\\*[\\s]*[\r\n]*/", ""); $doc = s($doc)->preg_replace("/[\r\n]*[\\s]*\\*\\/\$/", ""); } return (string) $doc; }
/** * @param \ReflectionProperty $property * * @return array */ public static function getPropertyTypes(\ReflectionProperty $property) { $doc = $property->getDocComment(); preg_match('/@var\\s([\\w\\\\|\\[\\]]+)/', $doc, $matches); $types = []; if (isset($matches[1])) { $types = explode('|', $matches[1]); } return $types; }
protected static function getPropertyType(\ReflectionProperty $property) { $comment = $property->getDocComment(); preg_match('/\\@var\\s+((\\w+)(\\[\\])*)/', $comment, $types); $type = $types[1]; // Class type if (!self::isPhpType($type)) { $type = self::qualifiedClass($property->getDeclaringClass(), $type); } return $type; }
/** * @param $className * @param $propertyName * @return array */ private static function getPropertyAnnotation($className, $propertyName) { $r = new \ReflectionProperty($className, $propertyName); $doc = $r->getDocComment(); preg_match_all('/@([\\w]*?)\\((.*?)\\)/s', $doc, $annotations); $a = []; for ($i = 0; $i < count($annotations[0]); $i++) { $a[$annotations[1][$i]] = $annotations[2][$i]; } return $a; }