public function __construct($class, $property) { $property = new ReflectionProperty($class, $property); list($description, $tags) = self::parse($property->getDocComment()); $this->data['title'] = $description[0]; $this->data['description'] = trim(implode("\n", $description)); if ($modifiers = $property->getModifiers()) { $this->data['modifiers'] = implode(' ', Reflection::getModifierNames($modifiers)); } else { $this->data['modifiers'] = 'public'; } if (isset($tags['var'])) { if (preg_match('/^(\\S*)(?:\\s*(.+?))?$/', $tags['var'][0], $matches)) { $this->data['type'] = $matches[1]; if (isset($matches[2])) { $this->data['description'] = array($matches[2]); } } } $this->data['name'] = $property->name; $this->data['class_name'] = $property->class; $this->data['is_static'] = $property->isStatic(); $this->data['is_public'] = $property->isPublic(); $class_rf = $property->getDeclaringClass(); if ($property->class != $class) { $this->data['is_php_class'] = $class_rf->getStartLine() ? 0 : 1; } else { $this->data['is_php_class'] = false; } $have_value = false; if ($property->isStatic()) { $v = $class_rf->getStaticProperties(); if (isset($v[$property->name])) { $value = $v[$property->name]; $have_value = true; } } else { if (!$property->isPrivate()) { if (!$class_rf->isFinal() && !$class_rf->isAbstract()) { $value = self::getValue($class, $property->name); $have_value = true; } } } if ($have_value) { $this->data['value'] = self::dump($value); $this->data['value_serialized'] = serialize($value); } }
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); }
/** * __set. * * Overloading method to set any $key property to $this->class or if not static, * to $this->object. * * @param $key * @param $value * @return $this */ public function __set($key, $value) { $property = new \ReflectionProperty($this->class, $key); $property->setAccessible(true); $property->isStatic() ? $property->setValue($value) : $property->setValue($this->object, $value); return $this; }
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)); } } }
/** * Make sure our class properties exist in extended classes. * * PHP doesn't accept abstract class properties, so this class method adds * this capability. */ protected final function _abstract_properties_validate() { //check if the child class has defined the abstract properties or not $child = get_class($this); foreach ($this->_abstract_properties as $name => $settings) { if (isset($settings['type']) && 'string' == $settings['type']) { if (isset($settings['static']) && true === $settings['static']) { $prop = new ReflectionProperty($child, $name); if (!$prop->isStatic()) { // property does not exist $error = $child . ' class must define $' . $name . ' property as static ' . $settings['type']; unset($prop, $child); throw new \LogicException($error); } } else { if (property_exists($this, $name) && strtolower(gettype($this->{$name})) == $settings['type']) { continue; } // property does not exist $error = $child . ' class must define $' . $name . ' property as ' . $settings['type']; throw new \LogicException($error); } } } unset($error, $child); }
function reflectProperty($class, $property) { $propInfo = new ReflectionProperty($class, $property); echo "**********************************\n"; echo "Reflecting on property {$class}::{$property}\n\n"; echo "__toString():\n"; var_dump($propInfo->__toString()); echo "export():\n"; var_dump(ReflectionProperty::export($class, $property, true)); echo "export():\n"; var_dump(ReflectionProperty::export($class, $property, false)); echo "getName():\n"; var_dump($propInfo->getName()); echo "isPublic():\n"; var_dump($propInfo->isPublic()); echo "isPrivate():\n"; var_dump($propInfo->isPrivate()); echo "isProtected():\n"; var_dump($propInfo->isProtected()); echo "isStatic():\n"; var_dump($propInfo->isStatic()); $instance = new $class(); if ($propInfo->isPublic()) { echo "getValue():\n"; var_dump($propInfo->getValue($instance)); $propInfo->setValue($instance, "NewValue"); echo "getValue() after a setValue():\n"; var_dump($propInfo->getValue($instance)); } echo "\n**********************************\n"; }
/** * Call to undefined method. * * @param string method name * @param array arguments * @return mixed * @throws \MemberAccessException */ public static function call($_this, $name, $args) { $class = get_class($_this); if ($name === '') { throw new MemberAccessException("Call to class '{$class}' method without name."); } // event functionality if (preg_match('#^on[A-Z]#', $name)) { $rp = new ReflectionProperty($class, $name); if ($rp->isPublic() && !$rp->isStatic()) { $list = $_this->{$name}; if (is_array($list) || $list instanceof Traversable) { foreach ($list as $handler) { /**/ fixCallback($handler); /**/ if (!is_callable($handler)) { $able = is_callable($handler, TRUE, $textual); throw new InvalidStateException("Event handler '{$textual}' is not " . ($able ? 'callable.' : 'valid PHP callback.')); } call_user_func_array($handler, $args); } } return NULL; } } // extension methods if ($cb = self::extensionMethod($class, $name)) { array_unshift($args, $_this); return call_user_func_array($cb, $args); } throw new MemberAccessException("Call to undefined method {$class}::{$name}()."); }
public function __call($name, $args) { $class = get_class($this); if ($name === '') { throw new MemberAccessException("Call to class '{$class}' method without name."); } if (preg_match('#^on[A-Z]#', $name)) { $rp = new ReflectionProperty($class, $name); if ($rp->isPublic() && !$rp->isStatic()) { $list = $this->{$name}; if (is_array($list) || $list instanceof Traversable) { foreach ($list as $handler) { if (is_object($handler)) { call_user_func_array(array($handler, '__invoke'), $args); } else { call_user_func_array($handler, $args); } } } return NULL; } } if ($cb = self::extensionMethod("{$class}::{$name}")) { array_unshift($args, $this); return call_user_func_array($cb, $args); } throw new MemberAccessException("Call to undefined method {$class}::{$name}()."); }
private function getProperty($classOrObject, $property) { $property = new \ReflectionProperty(is_object($classOrObject) ? get_class($classOrObject) : $classOrObject, $property); if (!$property->isPublic()) { $property->setAccessible(true); } return $property->isStatic() ? $property->getValue($classOrObject) : $property->getValue(); }
/** * Returns true if this property has is a static property. * * @return bool */ public function isStatic() { if ($this->reflectionSource instanceof ReflectionProperty) { return $this->reflectionSource->isStatic(); } else { return parent::isStatic(); } }
/** * @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; }
public function testPublicize_with_private_static_property() { $className = __FUNCTION__ . md5(uniqid()); eval(sprintf('class %s { private static $foo = "foo_value"; }', $className)); $reflectionProperty = new ReflectionProperty($className, 'foo'); $this->assertTrue($reflectionProperty->isStatic()); $this->assertTrue($reflectionProperty->isPrivate()); $this->assertSame($reflectionProperty, $reflectionProperty->publicize()); $this->assertSame('foo_value', $reflectionProperty->getValue($className)); }
protected function hydrate($data) { $reflection = new ReflectionClass($this); $fields = $reflection->getProperties(ReflectionProperty::IS_PUBLIC); foreach ($fields as $f) { $prop = $f->name; $met = new ReflectionProperty($this, $prop); if (!$met->isStatic()) { $this->{$prop} = $data[$prop]; } } }
function __construct(ReflectionProperty $property) { $this->name = $property->getName(); $this->is_public = $property->isPublic(); $this->is_private = $property->isPrivate(); $this->is_protected = $property->isProtected(); $this->is_static = $property->isStatic(); $this->declaring_class = API_Doc_Class::instance($property->getDeclaringClass()); list($comment, $meta) = $this->_docComment($property->getDocComment()); $this->_processDescription($comment); $this->_processMeta($meta); }
/** * 获取一个类属性值 * @param string $class * @param string $propertyName */ public static function getClassPropertyValue($class, $propertyName) { if (!property_exists($class, $propertyName)) { return null; } $reflectionProperty = new ReflectionProperty($class, $propertyName); if ($reflectionProperty->isStatic()) { return $reflectionProperty->getValue(); } else { $reflectionClass = new ReflectionClass($class); return $reflectionProperty->getValue($reflectionClass->newInstance($class)); } }
public static function fromReflection(\ReflectionProperty $ref) { $property = new static($ref->name); $property->setStatic($ref->isStatic())->setVisibility($ref->isPublic() ? self::VISIBILITY_PUBLIC : ($ref->isProtected() ? self::VISIBILITY_PROTECTED : self::VISIBILITY_PRIVATE)); $docblock = new Docblock($ref); $property->setDocblock($docblock); $property->setDescription($docblock->getShortDescription()); $defaultProperties = $ref->getDeclaringClass()->getDefaultProperties(); if (isset($defaultProperties[$ref->name])) { $property->setDefaultValue($defaultProperties[$ref->name]); } return $property; }
public static function fromReflection(\ReflectionProperty $ref) { $property = new static(); $property->setName($ref->name)->setStatic($ref->isStatic())->setVisibility($ref->isPublic() ? self::VISIBILITY_PUBLIC : ($ref->isProtected() ? self::VISIBILITY_PROTECTED : self::VISIBILITY_PRIVATE)); if ($docComment = $ref->getDocComment()) { $property->setDocblock(ReflectionUtils::getUnindentedDocComment($docComment)); } $defaultProperties = $ref->getDeclaringClass()->getDefaultProperties(); if (isset($defaultProperties[$ref->name])) { $property->setDefaultValue($defaultProperties[$ref->name]); } return $property; }
public function __construct(\ReflectionProperty $reflector) { $this->name = $reflector->name; $comment = $reflector->getDocComment(); $this->export = preg_match('/@Export\\s/', $comment) > 0; $this->isReadOnly = preg_match('/@ReadOnly\\s/', $comment) > 0; $this->isIdentifier = preg_match('/@Id\\s/', $comment) > 0; $this->isPublic = $reflector->isPublic(); $this->isStatic = $reflector->isStatic(); $defaultProperties = $reflector->getDeclaringClass()->getDefaultProperties(); if (isset($defaultProperties[$this->name])) { $this->defaultValue = $defaultProperties[$this->name]; } }
/** * Checks if the public non-static property exists. * * @return mixed */ private static function hasProperty($class, $name) { $prop =& self::$props[$class][$name]; if ($prop === null) { $prop = false; try { $rp = new \ReflectionProperty($class, $name); if ($name === $rp->getName() && $rp->isPublic() && !$rp->isStatic()) { $prop = preg_match('#^on[A-Z]#', $name) ? 'event' : true; } } catch (\ReflectionException $e) { } } return $prop; }
private function loadFromStorage() { $properties = $this->storage->loadProperties($this->getClassId()); foreach ($properties as $name => $value) { if (property_exists($this, $name)) { $ref = new \ReflectionProperty(get_class($this), $name); if ($ref->isStatic()) { static::${$name} = $value; } else { $this->{$name} = $value; } } else { $this->{$name} = $value; } } }
/** * @param \ReflectionProperty $property * @return Property */ public function property(\ReflectionProperty $property) { $phpyProperty = new Property($property->getName()); $phpyProperty->setStatic($property->isStatic()); $refClass = $property->getDeclaringClass(); $defClassValues = $refClass->getDefaultProperties(); if (isset($defClassValues[$property->getName()])) { $phpyProperty->setDefaultValue($defClassValues[$property->getName()]); } if ($property->isPublic()) { $phpyProperty->setVisibility('public'); } elseif ($property->isProtected()) { $phpyProperty->setVisibility('protected'); } else { $phpyProperty->setVisibility('private'); } return $phpyProperty; }
protected function buildFieldSignature(\ReflectionProperty $prop) : string { if ($prop->isProtected()) { $code = 'protected '; } elseif ($prop->isPrivate()) { $code = 'private '; } else { $code = 'public '; } if ($prop->isStatic()) { $code .= 'static '; } $code .= '$' . $prop->name; $defaults = $prop->getDeclaringClass()->getDefaultProperties(); if (array_key_exists($prop->name, $defaults)) { $code .= ' = ' . $this->buildLiteralCode($defaults[$prop->name]); } return $code; }
/** * @param \ReflectionMethod|\ReflectionProperty $element * @return bool */ private function filter($element, $static, $public_only) { if (!$element instanceof \ReflectionMethod && !$element instanceof \ReflectionProperty) { throw new \InvalidArgumentException('Parameter must be a member of ReflectionMethod or ReflectionProperty class'); } if ($static !== null && ($element->isStatic() xor $static)) { return false; } if ($element->isPublic()) { return true; } if ($public_only) { return false; } if ($element->isProtected()) { return true; } // $element is then private return $element->getDeclaringClass()->getName() === $this->getName(); }
public function __construct($class, $property) { $property = new ReflectionProperty($class, $property); list($description, $tags) = Docs::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 = $matches[2]; } } } $this->property = $property; if ($property->isStatic()) { $this->value = Docs::debug($property->getValue($class)); } }
function initLogger() { $loggerName = "log"; // Iterate over all declared classes $classes = get_declared_classes(); foreach ($classes as $class) { $reflection = new ReflectionClass($class); // If the class is internally defined by PHP or has no property called "logger", skip it. if ($reflection->isInternal() || !$reflection->hasProperty($loggerName)) { continue; } // Get information regarding the "logger" property of this class. $property = new ReflectionProperty($class, $loggerName); // If the "logger" property is not static or not public, then it is not the one we are interested in. Skip this class. if (!$property->isStatic() || !$property->isPublic()) { continue; } // Initialize the logger for this class. $reflection->setStaticPropertyValue($loggerName, getLogger()); } }
/** * takes a reflection property and returns a nicely formatted key of the property name * * @param ReflectionProperty * @return string */ protected function _getPropertyKey(ReflectionProperty $property) { $static = $property->isStatic() ? ' static' : ''; if ($property->isPublic()) { return 'public' . $static . ' ' . $property->getName(); } if ($property->isProtected()) { return 'protected' . $static . ' ' . $property->getName(); } if ($property->isPrivate()) { return 'private' . $static . ' ' . $property->getName(); } }
/** * Validate the object's properties according to the rules * defined in $_validation array. * * @return void|multitype:multitype: boolean */ function validate() { if (!property_exists($this, "_validation")) { return; } // Get table columns $table_columns = get_object_vars($this); $response = array("valid" => array(), "invalid" => array(), "success" => false); // Get validation rules that may be declared static $validation_rules = null; $prop_detail = new ReflectionProperty($this, "_validation"); if ($prop_detail->isStatic()) { $validation_rules = $this::$_validation; } else { $validation_rules = $this->_validation; } // Loop through defined validation rules foreach ($validation_rules as $vr_key => $arr_rules) { // Check that what the user has provided is in our object if (!array_key_exists($vr_key, $table_columns)) { continue; } // Switch the rules... maybe there's a better way to do this :) foreach ($arr_rules as $rule => $rule_array) { if (is_string($rule_array)) { $rule = $rule_array; } if (empty($this->{$vr_key}) && $rule !== "required") { continue; } switch ($rule) { case "required": if (empty($this->{$vr_key}) && !is_numeric($this->{$vr_key})) { $response["invalid"]["{$vr_key}"][] = "Required Field"; } else { $response["valid"][] = $vr_key; } break; case "number": // $this->$vr_key = filter_var($this->$vr_key, FILTER_SANITIZE_NUMBER_FLOAT); if (!filter_var($this->{$vr_key}, FILTER_VALIDATE_FLOAT)) { $response["invalid"]["{$vr_key}"][] = "Invalid Number"; } else { $response["valid"][] = $vr_key; } break; case "url": // please be aware that this may accept invalid urls // see http://www.php.net/manual/en/function.filter-var.php $this->{$vr_key} = filter_var($this->{$vr_key}, FILTER_SANITIZE_URL); if (!filter_var($this->{$vr_key}, FILTER_VALIDATE_URL)) { $response["invalid"]["{$vr_key}"][] = "Invalid URL"; } else { $response["valid"][] = $vr_key; } break; case "email": // please be aware that this may accept invalid emails // see http://www.php.net/manual/en/function.filter-var.php $this->{$vr_key} = filter_var($this->{$vr_key}, FILTER_SANITIZE_EMAIL); if (!filter_var($this->{$vr_key}, FILTER_VALIDATE_EMAIL)) { $response["invalid"]["{$vr_key}"][] = "Invalid Email"; } else { $response["valid"][] = $vr_key; } break; case "in": // Case insensitive field check against an array of predefined values if (is_array($rule_array)) { $this->{$vr_key} = filter_var($this->{$vr_key}, FILTER_SANITIZE_STRING); if (!in_array(ucfirst(strtolower($this->{$vr_key})), $rule_array)) { $response["invalid"]["{$vr_key}"][] = "Invalid value, allowed are " . implode(", ", $rule_array); } else { $response["valid"][] = $vr_key; } } break; case "unique": break; case "custom": case "regex": // Add surrounding regex slashes if they dont exist if ($rule[0] !== '/') { $rule = '/' . $rule; } if ($rule[strlen($rule) - 1] !== '/') { $rule = $rule . '/'; } if (!filter_var($this->{$vr_key}, FILTER_VALIDATE_REGEXP, array('regexp' => $rule))) { $response["invalid"]["{$vr_key}"][] = "Invalid"; } else { $response["valid"][] = $vr_key; } break; } } } // else do nothing and let execution proceed as usual // Set response value to if the validation was succesful if (count($response["invalid"]) == 0) { $response["success"] = true; } return $response; // die(); // debugging only // if validation fails return to invoked page with errors... how to transport them though? // this function is called deep in code so the initiator of the update or insert function may not know what's // going on ... redirecting away to another page from here is ... rude. // better to do the following: // - update or insert just fail but send an exception containing the invalid messages // - caller should call validate BEFORE update / insert to react to messages in a UI fashion (eg. redisplay form with message, etc) // if (count($response["invalid"]) > 0){ // $_SESSION["errors"] = $response["invalid"]; // <-- GENIUS!... hopefully that works // $this->w->redirect($this->w->localUrl($_SERVER["REDIRECT_URL"])); // } }
/** * @param string $class_name * @param string $property_name * * @return bool */ private function _has_own_static($class_name, $property_name) { $has_own_static_property = false; if (property_exists($class_name, $property_name)) { $reflected_property = new ReflectionProperty($class_name, $property_name); $has_own_static_property = $reflected_property->isStatic(); } return $has_own_static_property; }
function _pprintr_object_ReflectionProperty(ReflectionProperty $property, $var, $indent, $indentStep) { $modifiers = array(); $property->setAccessible(true); if (defined('PPRINTR_INCLUDE_PROTECTED') && PPRINTR_INCLUDE_PROTECTED) { $property->isPublic() && ($modifiers[] = "[92mpublic[0m"); $property->isProtected() && ($modifiers[] = "[91mprotected[0m"); $property->isPrivate() && ($modifiers[] = "[91mprivate[0m"); } $property->isStatic() && ($modifiers[] = "static"); $modifiers = implode(' ', $modifiers); $name = $property->getName(); $value = pprintr($property->getValue($var), $indent + $indentStep, $indentStep); $str = "[0m[1m{$name}[0m => {$value}"; if ($modifiers != []) { $str = "[0m{$modifiers}[1m {$str}"; } return $str; }
/** * @param object $object * @param \ReflectionProperty $property * @param int $level * @return string */ private function dumpProperty($object, \ReflectionProperty $property, $level) { if ($property->isStatic()) { return ''; } if (!$object instanceof \stdClass && strpos($property->getDocComment(), '@invisible') !== false) { //Memory loop while reading doc comment for stdClass variables? //Report a PHP bug about treating comment INSIDE property declaration as doc comment. return ''; } //Property access level $access = $this->getAccess($property); //To read private and protected properties $property->setAccessible(true); if ($object instanceof \stdClass) { $access = 'dynamic'; } //Property name includes access level $name = $property->getName() . $this->style->style(":" . $access, "access", $access); return $this->dumpValue($property->getValue($object), $name, $level + 1); }