/** * Returns an array of traits used by this class * @return array with trait names in keys and instances of trait's ReflectionClass in values. Returns NULL in case of an error. */ public function getTraits() { $traits = array(); if (method_exists('\\ReflectionClass', 'getTraits')) { $traits = parent::getTraits(); } return $traits; }
/** * Create a new Eloquent model instance, ensuring that any auditing * columns are guarded. * * @param array $attributes * @return void */ public function __construct(array $attributes = array()) { // if we're using the auditing trait, guard the audit columns $reflection = new \ReflectionClass($this); if (array_key_exists('BishopB\\Forum\\AuditingTrait', $reflection->getTraits())) { $this->guarded = $this->guarded + $this->getAuditors(); } parent::__construct($attributes); }
public function testDoubleOfInterface() { $obj_creator = new FBMock_TestDoubleCreator(); $obj = $obj_creator->createTestDoubleFor('TestInterfaceA', array('TestInterfaceB'), array('TestTrait1', 'TestTrait2')); $this->assertInstanceof('TestInterfaceA', $obj); $this->assertInstanceof('TestInterfaceB', $obj); $ref_class = new ReflectionClass($obj); self::assertEquals(array('TestTrait1', 'TestTrait2', 'FBMock_TestDoubleObject'), array_keys($ref_class->getTraits())); }
/** * Inspect trait. * * @return void */ protected function inspectTrait() { if (PHP_VERSION < '5.4') { return; } $traits = $this->class->getTraits(); if (!empty($traits)) { foreach ($traits as $trait) { $this->inspection['use'][] = $this->getInheritanceInspection($trait); } } }
/** * Gets a recursive list of traits used by a class * * @param string $class Full class name * * @return array */ private function getRecursiveTraits($class = null) { if (null == $class) { $class = get_class($this); } $reflection = new \ReflectionClass($class); $traits = array_keys($reflection->getTraits()); foreach ($traits as $trait) { $traits = array_merge($traits, $this->getRecursiveTraits($trait)); } if ($parent = $reflection->getParentClass()) { $traits = array_merge($traits, $this->getRecursiveTraits($parent->getName())); } return $traits; }
function index() { $model = base64_decode(\Route::input('model')); dump($model); $r = new \ReflectionClass($model); dd($r->getTraits()); $methods = []; foreach ($r->getMethods() as $method) { if ($method->class == $model) { $methods[] = $this->sourceMethod($method); } } dump($methods); dump($methods = $r->getMethod('messageNotFound')); dump($methods = $r->getMethod('messageNotFound')->getDocComment()); dump($this->sourceMethod($r->getMethod('messageNotFound'))); dump($methods = $r->getMethod('messageNotFound')->class); // $models = rglob('*.php', 0, base_path('vendor/*/*/*/*/Models/')); // dd(111, $models); return $this->response(['rows' => CrudRow::$rows]); }
public static function boot() { $elasticClient = ClientBuilder::create()->build(); $updateIndex = function (ElasticModel $modelInstance) use($elasticClient) { $params = ['index' => config('search.index'), 'type' => $modelInstance->getElasticType(), 'id' => $modelInstance->getKey(), 'body' => $modelInstance->toElasticArray()]; $elasticClient->index($params); return true; }; $deleteIndex = function (ElasticModel $modelInstance) use($elasticClient) { $reflectionClass = new \ReflectionClass($modelInstance); $traits = $reflectionClass->getTraits(); if (in_array(SoftDeletes::class, array_keys($traits)) && $modelInstance->trashed()) { return true; } $params = ['index' => config('search.index'), 'type' => $modelInstance->getElasticType(), 'id' => $modelInstance->getKey()]; $elasticClient->delete($params); return true; }; static::created($updateIndex); static::updated($updateIndex); static::deleted($deleteIndex); }
protected function findSummary(\ReflectionClass $scopeClass, \ReflectionMethod $scopeMethod, Language $lang = null, &$alreadyScopedClasses = array()) { foreach ($alreadyScopedClasses as $sc) { /* @var \ReflectionClass $sc */ if ($sc->getName() === $scopeClass->getName()) { return null; } } $alreadyScopedClasses[] = $scopeClass; $doc = new DocBlock($scopeMethod); $result = $doc->getShortDescription(); if ('{@inheritdoc}' === \trim(\strtolower($result))) { $result = null; $typesToCheck = \array_merge($scopeClass->getTraits(), [$scopeClass->getParentClass()], $scopeClass->getInterfaces()); foreach ($typesToCheck as $type) { if (!$type instanceof \ReflectionClass) { continue; } $matchingMethod = null; foreach ($type->getMethods() as $otherMethod) { if ($otherMethod->getName() !== $scopeMethod->getName()) { continue; } $matchingMethod = $otherMethod; } if (!$matchingMethod instanceof \ReflectionMethod) { continue; } $summary = \trim($this->findSummary($type, $matchingMethod, $lang, $alreadyScopedClasses)); if ('' !== $summary) { $result = $summary; } } } $result = \trim($result); return '' !== $result ? $result : null; }
/** * クラスのアノテーションを取得する * @param string $class 対象のクラス名 * @param string[] $names デコード対象のアノテーション名 * @param string $doc_name 説明を取得する場合の添字 * @param string $parent 遡る最上のクラス名 */ public static function get_class($class, $names, $doc_name = null, $parent = null) { $return = []; $t = new \ReflectionClass($class); $d = null; if (empty($parent)) { $parent = 'stdClass'; } while ($t->getName() != $parent) { $d = $t->getDocComment() . $d; foreach ($t->getTraits() as $trats) { $d = $trats->getDocComment() . $d; } $t = $t->getParentClass(); if ($t === false) { break; } } $d = preg_replace("/^[\\s]*\\*[\\s]{0,1}/m", '', str_replace(['/' . '**', '*' . '/'], '', $d)); foreach (is_array($names) ? $names : [$names] as $name) { $return[$name] = self::decode($d, $name, $doc_name); } return is_array($names) ? $return : $return[$names]; }
/** * Returns traits used by this class. * * @return array */ public function getTraits() { return NATIVE_TRAITS ? parent::getTraits() : array(); }
/** * load business properties from ReflectionClass. * * @return array **/ protected function loadBusinessProperties(\ReflectionClass $class) { $businessProperties = []; $properties = $class->getProperties(); $traits = $class->getTraits(); $className = $class->getName(); // if the class is translatable, then parse annotations on it's translation class if (array_key_exists(Translatable::class, $traits)) { $translation = new \ReflectionClass($className::getTranslationEntityClass()); $translationProperties = $translation->getProperties(); $properties = array_merge($properties, $translationProperties); } foreach ($properties as $property) { $annotations = $this->reader->getPropertyAnnotations($property); foreach ($annotations as $key => $annotationObj) { if ($annotationObj instanceof BusinessProperty && !in_array($class, $businessProperties)) { if (!$annotations[$key]->getTypes()) { $message = $class->name . ':$' . $property->name . '" field'; throw AnnotationException::requiredError('type', 'BusinessProperty annotation', $message, 'array or string'); } foreach ($annotations[$key]->getTypes() as $type) { $businessProperties[$type][] = $property->name; } } } } // we load business properties of parents recursively // because they are defined by an annotation not by the property type(private, protected, public) $parentClass = $class->getParentClass(); if ($parentClass) { //load parent properties recursively $parentProperties = $this->loadBusinessProperties(new \ReflectionClass($parentClass->getName())); foreach ($parentProperties as $key => $parentProperty) { if (array_key_exists($key, $businessProperties)) { //if parent and current have a same business property type we merge the properties and remove //duplicates if properties are the same; $businessProperties[$key] = array_unique(array_merge($parentProperty, $businessProperties[$key])); } else { //else we had a business property type for the parent properties $businessProperties[$key] = $parentProperty; } } } return $businessProperties; }
trait Trait1 { public function run() { } public function say() { } } trait Trait2 { public function run() { } public function say() { } } class MyClass { use Trait1, Trait2 { Trait1::run as execute; Trait1::say insteadof Trait2; Trait2::run insteadof Trait1; Trait2::say as talk; } } $ref = new ReflectionClass('MyClass'); print_r($ref->getTraitAliases()); print_r($ref->getTraits());
/** * Tests if all entity fields are registered. */ public function testAllEntityFieldsRegistered() { $reflect = new \ReflectionClass($this->getClassName()); $properties = $reflect->getProperties(); $fields = []; /** @var \ReflectionProperty $property */ foreach ($properties as $property) { $fields[] = $property->getName(); } $parentClass = $reflect->getParentClass(); if ($parentClass) { $parentClassProperties = $parentClass->getProperties(); /** @var \ReflectionProperty $property */ foreach ($parentClassProperties as $property) { $this->addIgnoredFields($property->getName()); } } $traits = $reflect->getTraits(); if ($traits) { foreach ($traits as $trait) { $traitProperties = $trait->getProperties(); /** @var \ReflectionProperty $property */ foreach ($traitProperties as $property) { $this->addIgnoredFields($property->getName()); } } } $registeredFields = []; foreach ($this->getFieldsData() as $data) { $registeredFields[] = $data[0]; } $diff = array_diff($fields, $registeredFields, $this->getIgnoredFields()); if (count($diff) !== 0) { $this->fail(sprintf('All entity fields must be registered in test. Please check field(s) "%s".', implode('", "', $diff))); } }
/** * Check if reflection class has LinkTrait. * * @param \ReflectionClass $reflect * * @return bool */ private function hasLinkTrait(\ReflectionClass $reflect) { $linkTraitName = 'Victoire\\Bundle\\WidgetBundle\\Entity\\Traits\\LinkTrait'; $traits = $reflect->getTraits(); foreach ($traits as $trait) { if ($trait->getName() == $linkTraitName) { return true; } } if ($parentClass = $reflect->getParentClass()) { if ($this->hasLinkTrait($parentClass)) { return true; } } return false; }
/** * Retrieve the classes and defining files the given class depends on (including the given class) * * @param ReflectionClass The class to get the dependend classes for. * @param callable A callback function which takes a file name as argument * and returns whether the file is blacklisted. * * @return string[] An array containing class names as keys and path to the * file's defining class as value. * * @author Dominik del Bondio <*****@*****.**> * @since 1.1.0 */ private function getClassDependendFiles(ReflectionClass $reflectionClass, $isBlacklisted) { $requires = array(); while ($reflectionClass) { $file = $reflectionClass->getFileName(); // we don't care for duplicates since we're using require_once anyways if (!$isBlacklisted($file) && is_file($file)) { $requires[$reflectionClass->getName()] = $file; } foreach ($reflectionClass->getInterfaces() as $interface) { $file = $interface->getFileName(); $requires = array_merge($requires, $this->getClassDependendFiles($interface, $isBlacklisted)); } if (is_callable(array($reflectionClass, 'getTraits'))) { // FIXME: remove check after bumping php requirement to 5.4 foreach ($reflectionClass->getTraits() as $trait) { $file = $trait->getFileName(); $requires = array_merge($requires, $this->getClassDependendFiles($trait, $isBlacklisted)); } } $reflectionClass = $reflectionClass->getParentClass(); } return $requires; }
<?php trait P1 { private $p1; } trait C1 { private $c1; } class P2 { use P1; private $p2; } class C2 extends P2 { use C1; private $c2; } $p = new ReflectionClass(new P2()); var_dump($p->hasProperty('p2')); var_dump($p->hasProperty('p1')); var_dump($p->getTraits()['P1']->hasProperty('p1')); $c = new ReflectionClass(new C2()); var_dump($c->hasProperty('p2')); var_dump($c->hasProperty('p1')); var_dump(isset($c->getTraits()['P1'])); var_dump($c->getTraits()['C1']->hasProperty('c1'));
<?php trait T1 { } trait T2 { } class C1 { } class C2 { use T1; } class C3 { use T1; use T2; } for ($c = "C1"; $c <= "C3"; $c++) { echo "class {$c}:\n"; $r = new ReflectionClass($c); var_dump($r->getTraitNames()); var_dump($r->getTraits()); echo "\n"; }
/** * @param \ReflectionClass $Rc * @return \ReflectionClass[] */ private static function recursiveGetTraits(\ReflectionClass $Rc) { foreach ($Rc->getTraits() as $Trait) { (yield $Trait); foreach (self::recursiveGetTraits($Trait) as $T) { (yield $T); } } }
/** * Wraps ReflectionClass::getTraits to return an AnnotationClass object * instead of a ReflectionClass object. * * @access public * @return array Returns an array with trait names in keys and objects of trait's AnnotationClass in values. Returns NULL in case of an error. */ public function getTraits() { if ($traits = parent::getTraits()) { return array_map(function ($object) { return new AnnotationClass($object); }, $traits); } return null; }
/** * @param string $className * @param string $methodName * * @return array * * @throws ReflectionException * * @since Method available since Release 3.4.0 */ public static function parseTestMethodAnnotations($className, $methodName = '') { if (!isset(self::$annotationCache[$className])) { $class = new ReflectionClass($className); $traits = $class->getTraits(); $annotations = []; foreach ($traits as $trait) { $annotations = array_merge($annotations, self::parseAnnotations($trait->getDocComment())); } self::$annotationCache[$className] = array_merge($annotations, self::parseAnnotations($class->getDocComment())); } if (!empty($methodName) && !isset(self::$annotationCache[$className . '::' . $methodName])) { try { $method = new ReflectionMethod($className, $methodName); $annotations = self::parseAnnotations($method->getDocComment()); } catch (ReflectionException $e) { $annotations = []; } self::$annotationCache[$className . '::' . $methodName] = $annotations; } return ['class' => self::$annotationCache[$className], 'method' => !empty($methodName) ? self::$annotationCache[$className . '::' . $methodName] : []]; }
/** * {@inheritdoc} */ public function getTraits() { return $this->reflectionClass->getTraits(); }
/** * @param string $interfaceOrClass * * @return string|null */ protected function getClassDefinition($interfaceOrClass) { $reflectionClass = new \ReflectionClass($interfaceOrClass); if ($reflectionClass->isFinal() or $reflectionClass->isTrait()) { return; } $namespace = $this->namespace . '\\' . $reflectionClass->getNamespaceName(); $name = $reflectionClass->getShortName(); $trait = ''; if (!array_key_exists($this->trait, $reflectionClass->getTraits())) { $trait = 'use \\' . $this->trait . ';'; } $keyword = $reflectionClass->isInterface() ? 'implements' : 'extends'; $base = '\\' . $reflectionClass->getName(); $methods = []; foreach ($reflectionClass->getMethods() as $reflectionMethod) { $methods[] = $this->getMethodDefinition($reflectionMethod); } if (empty($methods)) { return; } $methods = array_filter($methods); $methods = implode("\n", $methods); $replace = ['{$namespace}' => $namespace, '{$name}' => $name, '{$trait}' => $trait, '{$keyword}' => $keyword, '{$base}' => $base, '{$methods}' => $methods]; $template = $this->classTemplate; $definition = str_replace(array_keys($replace), array_values($replace), $template); return $definition; }
private function setReflectionPropertiesFromData(array $data, \ReflectionClass $reflectionClass, $object) { foreach ($reflectionClass->getProperties() as $reflectionProperty) { if (!array_key_exists($reflectionProperty->getName(), $data)) { continue; } $property = new ReflectionPropertyHelper($reflectionClass, $reflectionProperty); if ($property->isSkipped()) { continue; } if ($property->isArray() && $property->isObject()) { $values = array_map(function ($value) use($property) { if ($value instanceof \ArrayObject) { $value = $value->getArrayCopy(); } return $this->deserialize($property->getType(), $value); }, $data[$reflectionProperty->getName()]); $property->setValue($object, $values); } elseif ($property->isObject()) { $value = !is_null($data[$reflectionProperty->getName()]) ? $this->deserialize($property->getType(), $data[$reflectionProperty->getName()]) : null; $property->setValue($object, $value); } else { $property->setValue($object, $data[$reflectionProperty->getName()]); } unset($data[$reflectionProperty->getName()]); } if (false !== ($parentClass = $reflectionClass->getParentClass())) { $object = $this->setReflectionPropertiesFromData($data, $parentClass, $object); } foreach ($reflectionClass->getTraits() as $traitReflectionClass) { $object = $this->setReflectionPropertiesFromData($data, $traitReflectionClass, $object); } return $object; }
/** * Add the class's traits to the manifest */ private function finaliseTraits() { $ref = new \ReflectionClass($this->class); foreach ($ref->getTraits() as $traitReflector) { $entry = new self($traitReflector->getName(), null, $this->manifest); $entry->finalise(); $this->methods = array_merge($this->methods, $entry->methods); $this->properties = array_merge($this->properties, $entry->properties); $this->identifiers = array_merge($this->identifiers, $entry->identifiers); $this->constants = array_merge($this->constants, $entry->constants); } }
/** * Returns array of magic properties defined by annotation @property. * @return array of [name => bit mask] */ public static function getMagicProperties($class) { static $cache; $props =& $cache[$class]; if ($props !== NULL) { return $props; } $rc = new \ReflectionClass($class); preg_match_all('~^ [ \\t*]* @property(|-read|-write) [ \\t]+ [^\\s$]+ [ \\t]+ \\$ (\\w+) ()~mx', (string) $rc->getDocComment(), $matches, PREG_SET_ORDER); $props = []; foreach ($matches as list(, $type, $name)) { $uname = ucfirst($name); $write = $type !== '-read' && $rc->hasMethod($nm = 'set' . $uname) && ($rm = $rc->getMethod($nm)) && $rm->getName() === $nm && !$rm->isPrivate() && !$rm->isStatic(); $read = $type !== '-write' && ($rc->hasMethod($nm = 'get' . $uname) || $rc->hasMethod($nm = 'is' . $uname)) && ($rm = $rc->getMethod($nm)) && $rm->getName() === $nm && !$rm->isPrivate() && !$rm->isStatic(); if ($read || $write) { $props[$name] = $read << 0 | ($nm[0] === 'g') << 1 | $rm->returnsReference() << 2 | $write << 3; } } foreach ($rc->getTraits() as $trait) { $props += self::getMagicProperties($trait->getName()); } if ($parent = get_parent_class($class)) { $props += self::getMagicProperties($parent); } return $props; }
/** * Tests traits support comparing with the internal reflection. * * For PHP 5.4+ only. */ public function testTraits() { if (PHP_VERSION_ID < 50400) { $this->markTestSkipped('Requires PHP 5.4 or higher.'); } static $classes = array('TokenReflection_Test_ClassTraitsTrait1', 'TokenReflection_Test_ClassTraitsTrait2', 'TokenReflection_Test_ClassTraitsTrait3', 'TokenReflection_Test_ClassTraitsTrait4', 'TokenReflection_Test_ClassTraits', 'TokenReflection_Test_ClassTraits2', 'TokenReflection_Test_ClassTraits3', 'TokenReflection_Test_ClassTraits4'); require_once $this->getFilePath('traits'); $this->getBroker()->process($this->getFilePath('traits')); foreach ($classes as $className) { $token = $this->getBroker()->getClass($className); $internal = new \ReflectionClass($className); $this->assertSame($internal->isTrait(), $token->isTrait(), $className); $this->assertSame($internal->getTraitAliases(), $token->getTraitAliases(), $className); $this->assertSame($internal->getTraitNames(), $token->getTraitNames(), $className); $this->assertSame(count($internal->getTraits()), count($token->getTraits()), $className); foreach ($internal->getTraits() as $trait) { $this->assertTrue($token->usesTrait($trait->getName()), $className); } } }
private static function getTraits(\ReflectionClass $class) { $traits = $class->getTraits(); $classes = array(); while ($trait = array_pop($traits)) { if ($trait->isUserDefined() && !isset(self::$seen[$trait->getName()])) { $classes[] = $trait; $traits = array_merge($traits, $trait->getTraits()); } } return $classes; }
public function testGetTraits_just_returns_empty_array_lower_than_php5_4() { // fixture $class = __FUNCTION__ . md5(uniqid()); eval("class {$class} {}"); // expectation $expected = array(); $reflectionClass = new ReflectionClass($class); $actual = $reflectionClass->getTraits(); $this->assertEquals($expected, $actual); }
private static function computeTraitDeps(ReflectionClass $class) { $traits = $class->getTraits(); $deps = array($class->getName() => $traits); while ($trait = array_pop($traits)) { if ($trait->isUserDefined() && !isset(self::$seen[$trait->getName()])) { self::$seen[$trait->getName()] = true; $traitDeps = $trait->getTraits(); $deps[$trait->getName()] = $traitDeps; $traits = array_merge($traits, $traitDeps); } } return $deps; }
protected function getClassmap($name) { //error_log ("Getting classmap for: {$name}"); $reflect = new \ReflectionClass(new BaseProfile()); $traits = $reflect->getTraits(); //error_log ('Traits: ' . json_encode ($traits)); //error_log ("Reflecting in {$reflect->getName()}"); foreach ($traits as $k => $trait) { $props = $trait->getProperties(); //error_log ('Trait Props: ' . json_encode ($props)); foreach ($props as $prop) { //error_log ("{$prop->name} | {$name}"); if (trim("{$prop->name}") === trim("{$name}")) { $class = $prop->class; $class = str_ireplace("openlibrary\\", '', $class); $class = str_ireplace("metadata\\", '', $class); $class = str_ireplace("profiles\\", '', $class); $class = str_ireplace("properties\\", '', $class); $class = str_ireplace("ubc\\", '', $class); $class = str_ireplace("lsit\\", '', $class); $class = str_ireplace("resources\\", '', $class); $class = str_ireplace("schemas\\", '', $class); $class = str_ireplace("dpla\\", 'dpla:', $class); $class = str_ireplace("edm\\", 'edm:', $class); $class = str_ireplace("fi\\", 'fi:', $class); $class = str_ireplace("oa\\", 'oa:', $class); $class = str_ireplace("oc\\", 'oc:', $class); $class = str_ireplace("opencollections\\", 'oc:', $class); $class = str_ireplace("ore\\", 'ore:', $class); $class = str_ireplace("skos\\", 'skos:', $class); $class = str_ireplace("vivo\\", 'vivo:', $class); return $class; } } } return "unmapped:{$name}"; }