/** * Exports the PHP code * * @return string */ public function exportCode() { $code_lines = array(); $code_lines[] = '<?php'; // Export the namespace if ($this->_reflection_class->getNamespaceName()) { $code_lines[] = ''; $code_lines[] = 'namespace ' . $this->_reflection_class->getNamespaceName() . ';'; $code_lines[] = ''; } // Export the class' signature $code_lines[] = sprintf('%s%s%s %s%s%s', $this->_reflection_class->isAbstract() ? 'abstract ' : '', $this->_reflection_class->isFinal() ? 'final ' : '', $this->_reflection_class->isInterface() ? 'interface' : ($this->_reflection_class->isTrait() ? 'trait' : 'class'), $this->getClassName(), $this->_getParentClassName() ? " extends {$this->_getParentClassName()}" : '', $this->_getInterfaceNames() ? " implements " . join(', ', $this->_getInterfaceNames()) : ''); $code_lines[] = '{'; $code_lines[] = ''; // Export constants foreach ($this->_reflection_class->getConstants() as $name => $value) { $reflection_constant = new ReflectionConstant($name, $value); $code_lines[] = "\t" . $reflection_constant->exportCode(); $code_lines[] = ''; } // Export properties foreach ($this->_reflection_class->getProperties() as $property) { $reflection_property = new ReflectionProperty($property); $code_lines[] = "\t" . $reflection_property->exportCode(); $code_lines[] = ''; } // Export methods foreach ($this->_reflection_class->getMethods() as $method) { $reflection_method = new ReflectionMethod($method); $code_lines[] = "\t" . $reflection_method->exportCode(); $code_lines[] = ''; } $code_lines[] = '}'; return join("\n", $code_lines); }
/** * Creates a PHP class from reflection * * @param \ReflectionClass $ref * @return PhpClass */ public static function fromReflection(\ReflectionClass $ref) { $class = new static(); $class->setQualifiedName($ref->name)->setAbstract($ref->isAbstract())->setFinal($ref->isFinal())->setUseStatements(ReflectionUtils::getUseStatements($ref)); if ($ref->getDocComment()) { $docblock = new Docblock($ref); $class->setDocblock($docblock); $class->setDescription($docblock->getShortDescription()); $class->setLongDescription($docblock->getLongDescription()); } // methods foreach ($ref->getMethods() as $method) { $class->setMethod(static::createMethod($method)); } // properties foreach ($ref->getProperties() as $property) { $class->setProperty(static::createProperty($property)); } // traits foreach ($ref->getTraits() as $trait) { $class->addTrait(PhpTrait::fromReflection($trait)); } // constants // TODO: https://github.com/gossi/php-code-generator/issues/19 $class->setConstants($ref->getConstants()); return $class; }
protected static function mockImpl($type_, array $args_ = []) { $type = new \ReflectionClass($type_); if ($type->isFinal()) { throw new Exception_IllegalArgument('mock/factory', 'Can not mock final class.'); } $mtime = @filemtime($type->getFileName()); $classMock = 'Mock_' . str_replace('\\', '_', $type->getNamespaceName()) . '_' . $type->getShortName() . "_{$mtime}"; if (false === @class_exists($classMock)) { if (null === self::$m_tmpPath) { self::$m_tmpPath = (string) Test_Runner::get()->getTempPath(); } $fileName = self::$m_tmpPath . "/{$classMock}.php"; if (false === @file_exists($fileName)) { $source = self::weaveMock($classMock, new \ReflectionClass('Components\\Mock'), $type); if (false === @file_put_contents($fileName, $source, 0644)) { throw new Exception_IllegalState('mock/factory', sprintf('Unable to create mock [type: %1$s, path: %2$s].', $type_, $fileName)); } } require_once $fileName; } $classMock = "Components\\{$classMock}"; if (0 < count($args_)) { $refl = new \ReflectionClass($classMock); $mock = $refl->newInstanceArgs($args_); } else { $mock = new $classMock(); } $mock->mockType = $type; return $mock; }
/** * @param \ReflectionClass|string * @return self */ public static function from($from) { $from = new \ReflectionClass($from instanceof \ReflectionClass ? $from->getName() : $from); if (PHP_VERSION_ID >= 70000 && $from->isAnonymous()) { $class = new static('anonymous'); } else { $class = new static($from->getShortName(), new PhpNamespace($from->getNamespaceName())); } $class->type = $from->isInterface() ? 'interface' : (PHP_VERSION_ID >= 50400 && $from->isTrait() ? 'trait' : 'class'); $class->final = $from->isFinal() && $class->type === 'class'; $class->abstract = $from->isAbstract() && $class->type === 'class'; $class->implements = $from->getInterfaceNames(); $class->documents = $from->getDocComment() ? array(preg_replace('#^\\s*\\* ?#m', '', trim($from->getDocComment(), "/* \r\n\t"))) : array(); if ($from->getParentClass()) { $class->extends = $from->getParentClass()->getName(); $class->implements = array_diff($class->implements, $from->getParentClass()->getInterfaceNames()); } foreach ($from->getProperties() as $prop) { if ($prop->getDeclaringClass()->getName() === $from->getName()) { $class->properties[$prop->getName()] = Property::from($prop); } } foreach ($from->getMethods() as $method) { if ($method->getDeclaringClass()->getName() === $from->getName()) { $class->methods[$method->getName()] = Method::from($method)->setNamespace($class->namespace); } } return $class; }
public static function fromReflection(\ReflectionClass $ref) { $class = new static(); $class->setName($ref->name)->setAbstract($ref->isAbstract())->setFinal($ref->isFinal())->setConstants($ref->getConstants()); if (null === self::$phpParser) { if (!class_exists('Doctrine\\Common\\Annotations\\PhpParser')) { self::$phpParser = false; } else { self::$phpParser = new PhpParser(); } } if (false !== self::$phpParser) { $class->setUseStatements(self::$phpParser->parseClass($ref)); } if ($docComment = $ref->getDocComment()) { $class->setDocblock(ReflectionUtils::getUnindentedDocComment($docComment)); } foreach ($ref->getMethods() as $method) { $class->setMethod(static::createMethod($method)); } foreach ($ref->getProperties() as $property) { $class->setProperty(static::createProperty($property)); } return $class; }
function classData(ReflectionClass $class) { $details = ""; $name = $class->getName(); if ($class->isUserDefined()) { $details .= "{$name} is user defined\n"; } if ($class->isInternal()) { $details .= "{$name} is built-in\n"; } if ($class->isInterface()) { $details .= "{$name} is interface\n"; } if ($class->isAbstract()) { $details .= "{$name} is an abstract class\n"; } if ($class->isFinal()) { $details .= "{$name} is a final class\n"; } if ($class->isInstantiable()) { $details .= "{$name} can be instantiated\n"; } else { $details .= "{$name} can not be instantiated\n"; } return $details; }
/** * {@inheritdoc} */ protected function addRepository(ContainerBuilder $container, MetadataInterface $metadata) { $reflection = new \ReflectionClass($metadata->getClass('model')); $translatableInterface = TranslatableInterface::class; $translatable = interface_exists($translatableInterface) && $reflection->implementsInterface($translatableInterface); $repositoryClassParameterName = sprintf('%s.repository.%s.class', $metadata->getApplicationName(), $metadata->getName()); $repositoryClass = $translatable ? TranslatableResourceRepository::class : EntityRepository::class; if ($container->hasParameter($repositoryClassParameterName)) { $repositoryClass = $container->getParameter($repositoryClassParameterName); } if ($metadata->hasClass('repository')) { $repositoryClass = $metadata->getClass('repository'); } $repositoryReflection = new \ReflectionClass($repositoryClass); $definition = new Definition($repositoryClass); $definition->setArguments([new Reference($metadata->getServiceId('manager')), $this->getClassMetadataDefinition($metadata)]); $definition->setLazy(!$repositoryReflection->isFinal()); if ($metadata->hasParameter('translation')) { $translatableRepositoryInterface = TranslatableResourceRepositoryInterface::class; $translationConfig = $metadata->getParameter('translation'); if (interface_exists($translatableRepositoryInterface) && $repositoryReflection->implementsInterface($translatableRepositoryInterface)) { if (isset($translationConfig['fields'])) { $definition->addMethodCall('setTranslatableFields', [$translationConfig['fields']]); } } } $container->setDefinition($metadata->getServiceId('repository'), $definition); }
/** * Testing annotations. * * @test * @covers \Bairwell\Hydrator\Annotations\From */ public function testAnnotations() { $sut = new From(); $reflection = new \ReflectionClass($sut); $this->assertTrue($reflection->isFinal()); $properties = $reflection->getDefaultProperties(); $expectedProperties = ['sources' => [], 'field' => null, 'conditions' => []]; foreach ($expectedProperties as $k => $v) { $this->assertArrayHasKey($k, $properties); $this->assertEquals($v, $properties[$k]); } $comments = $reflection->getDocComment(); $expected = preg_quote('@Annotation'); $results = preg_match_all('/(\\n|\\r)\\s*\\*\\s+' . $expected . '\\s*(\\n|\\r)/', $comments, $matches); $this->assertEquals(1, $results); $expected = preg_quote('@Target({"PROPERTY"})'); $this->assertEquals(1, preg_match_all('/(\\n|\\r)\\s*\\*\\s+' . $expected . '\\s*(\\n|\\r)/', $comments, $matches)); // $property = $reflection->getProperty('sources'); $comments = $property->getDocComment(); $expected = '@var\\s+array'; $this->assertEquals(1, preg_match_all('/(\\n|\\r)\\s*\\*\\s+' . $expected . '\\s*(\\n|\\r)/', $comments, $matches)); $expected = '@Required'; $this->assertEquals(1, preg_match_all('/(\\n|\\r)\\s*\\*\\s+' . $expected . '\\s*(\\n|\\r)/', $comments, $matches)); // field $property = $reflection->getProperty('field'); $comments = $property->getDocComment(); $expected = '@var\\s+string'; $this->assertEquals(1, preg_match_all('/(\\n|\\r)\\s*\\*\\s+' . $expected . '\\s*(\\n|\\r)/', $comments, $matches)); // conditions $property = $reflection->getProperty('conditions'); $comments = $property->getDocComment(); $expected = '@var\\s+array'; $this->assertEquals(1, preg_match_all('/(\\n|\\r)\\s*\\*\\s+' . $expected . '\\s*(\\n|\\r)/', $comments, $matches)); }
/** * @return string */ public function getTitle() { if ($this->_classReflector->isInterface()) { $prefix = 'Interface'; } elseif ($this->_classReflector->isFinal()) { $prefix = 'Final class'; } elseif ($this->_classReflector->isAbstract()) { $prefix = 'Abstract class'; } else { $prefix = 'Class'; } $rstClassName = str_replace("\\", "\\\\", $this->_className); $rstTitle = "{$prefix} **{$rstClassName}**" . PHP_EOL; $rstTitle .= str_repeat('=', strlen($rstTitle) - strlen(PHP_EOL)) . PHP_EOL . PHP_EOL; return $rstTitle; }
private function isFinal($inheritedClass) { if (!class_exists($inheritedClass)) { return false; } $klass = new \ReflectionClass($inheritedClass); return $klass->isFinal(); }
protected function addProvider(ContainerBuilder $container, $providerClass, $modelName) { $providerReflection = new \ReflectionClass($providerClass); $definition = new Definition($providerClass); $definition->setArguments([new Reference(sprintf('%s.repository.%s', $this->applicationName, $modelName)), new Reference(sprintf('%s.factory.%s', $this->applicationName, $modelName))]); $definition->setLazy(!$providerReflection->isFinal()); $container->setDefinition(sprintf('%s.provider.%s', $this->applicationName, $modelName), $definition); }
/** * Filter out Interceptors defined for abstract classes * * @param string[] $interceptedEntities * @return string[] */ private function filterOutAbstractClasses($interceptedEntities) { $interceptedEntitiesFiltered = []; foreach ($interceptedEntities as $interceptorClass) { $interceptedEntity = substr($interceptorClass, 0, -12); $reflectionInterceptedEntity = new \ReflectionClass($interceptedEntity); if (!$reflectionInterceptedEntity->isAbstract() && !$reflectionInterceptedEntity->isFinal()) { $interceptedEntitiesFiltered[] = $interceptorClass; } } return $interceptedEntitiesFiltered; }
/** * Create a new doc reader * @param $class */ public function __construct($class) { $reflection = new ReflectionClass($class); self::read($reflection->getDocComment(), $this->tags, $this->comments); $this->isFinal = $reflection->isFinal(); $this->name = $reflection->getName(); $this->file = $reflection->getFileName(); $this->method_comments = array(); $this->method_tags = array(); foreach ($reflection->getMethods() as $method) { self::read($method->getDocComment(), $this->method_tags[$method->getName()], $this->method_comments[$method->getName()]); } }
/** * Generates a Mock Object class with all Mockery methods whose * intent is basically to provide the mock object with the same * class type hierarchy as a typical instance of the class being * mocked. * * @param string $className * @param string $mockName * @param string $allowFinal */ public static function createClassMock($className, $mockName = null, $allowFinal = false) { if (is_null($mockName)) { $mockName = uniqid('Mockery_'); } $class = new \ReflectionClass($className); $definition = ''; if ($class->isFinal() && !$allowFinal) { throw new \Mockery\Exception('The class ' . $className . ' is marked final and its methods' . ' cannot be replaced. Classes marked final can be passed in' . 'to \\Mockery::mock() as instantiated objects to create a' . ' partial mock, but only if the mock is not subject to type' . ' hinting checks.'); } elseif ($class->isFinal()) { $className = '\\Mockery\\Mock'; } $hasFinalMethods = false; $methods = $class->getMethods(\ReflectionMethod::IS_PUBLIC); $protected = $class->getMethods(\ReflectionMethod::IS_PROTECTED); foreach ($methods as $method) { if ($method->isFinal() && !$allowFinal) { throw new \Mockery\Exception('The method ' . $method->getName() . ' is marked final and it is not possible to generate a ' . 'mock object with such a method defined. You should instead ' . 'pass an instance of this object to Mockery to create a ' . 'partial mock.'); } elseif ($method->isFinal()) { $className = '\\Mockery\\Mock'; $hasFinalMethods = true; } } if ($class->isInterface()) { $inheritance = ' implements ' . $className . ', \\Mockery\\MockInterface'; } elseif ($class->isFinal() || $hasFinalMethods) { $inheritance = ' extends ' . $className; } else { $inheritance = ' extends ' . $className . ' implements \\Mockery\\MockInterface'; } $definition .= 'class ' . $mockName . $inheritance . PHP_EOL . '{' . PHP_EOL; if (!$class->isFinal() && !$hasFinalMethods) { $definition .= self::applyMockeryTo($class, $methods); $definition .= self::stubAbstractProtected($protected); } $definition .= PHP_EOL . '}'; eval($definition); return $mockName; }
/** * {@inheritdoc} */ protected function addRepository(ContainerBuilder $container, MetadataInterface $metadata) { $modelClass = $metadata->getClass('model'); $repositoryClass = in_array(TranslatableInterface::class, class_implements($modelClass)) ? TranslatableRepository::class : new Parameter('sylius.mongodb.odm.repository.class'); if ($metadata->hasClass('repository')) { $repositoryClass = $metadata->getClass('repository'); } $repositoryReflection = new \ReflectionClass($repositoryClass); $unitOfWorkDefinition = new Definition('Doctrine\\ODM\\MongoDB\\UnitOfWork'); $unitOfWorkDefinition->setFactory([new Reference($this->getManagerServiceId($metadata)), 'getUnitOfWork'])->setPublic(false); $definition = new Definition($repositoryClass); $definition->setArguments([new Reference($metadata->getServiceId('manager')), $unitOfWorkDefinition, $this->getClassMetadataDefinition($metadata)]); $definition->setLazy(!$repositoryReflection->isFinal()); $container->setDefinition($metadata->getServiceId('repository'), $definition); }
/** * {@inheritdoc} */ protected function addRepository(ContainerBuilder $container, MetadataInterface $metadata) { $repositoryClassParameterName = sprintf('%s.repository.%s.class', $metadata->getApplicationName(), $metadata->getName()); $repositoryClass = EntityRepository::class; if ($container->hasParameter($repositoryClassParameterName)) { $repositoryClass = $container->getParameter($repositoryClassParameterName); } if ($metadata->hasClass('repository')) { $repositoryClass = $metadata->getClass('repository'); } $repositoryReflection = new \ReflectionClass($repositoryClass); $definition = new Definition($repositoryClass); $definition->setArguments([new Reference($metadata->getServiceId('manager')), $this->getClassMetadataDefinition($metadata)]); $definition->setLazy(!$repositoryReflection->isFinal()); $container->setDefinition($metadata->getServiceId('repository'), $definition); }
/** * Get intercepted class names * * @param array $classes * @param array $interceptedEntities * @return array */ public function collectEntities(array $classes, array $interceptedEntities = []) { $output = []; foreach ($classes as $class) { foreach ($interceptedEntities as $interceptorClass) { $interceptedEntity = substr($interceptorClass, 0, -12); if (is_subclass_of($class, $interceptedEntity)) { $reflectionClass = new \ReflectionClass($class); if (!$reflectionClass->isAbstract() && !$reflectionClass->isFinal()) { $output[] = $class . '\\Interceptor'; } } } } $output = array_merge($interceptedEntities, $output); $output = array_unique($output); return $output; }
function add_class($class_name, $flags) { global $classes, $internal_arginfo; $lc = strtolower($class_name); $class = new \ReflectionClass($class_name); if ($class->isFinal()) { $flags |= \ast\flags\CLASS_FINAL; } if ($class->isAbstract()) { $flags |= \ast\flags\CLASS_ABSTRACT; } $classes[$lc] = ['file' => 'internal', 'conditional' => false, 'flags' => $flags, 'lineno' => 0, 'endLineno' => 0, 'name' => $class_name, 'docComment' => '', 'traits' => []]; foreach ($class->getDefaultProperties() as $name => $value) { $prop = new \ReflectionProperty($class_name, $name); $classes[$lc]['properties'][strtolower($name)] = ['flags' => $prop->getModifiers(), 'name' => $name, 'lineno' => 0, 'value' => $value]; } foreach ($class->getConstants() as $name => $value) { $classes[$lc]['constants'][strtolower($name)] = ['name' => $name, 'lineno' => 0, 'value' => $value]; } foreach ($class->getMethods() as $method) { $meth = new \ReflectionMethod($class_name, $method->name); $required = $meth->getNumberOfRequiredParameters(); $optional = $meth->getNumberOfParameters() - $required; $lmname = strtolower($method->name); $classes[$lc]['methods'][$lmname] = ['file' => 'internal', 'conditional' => false, 'flags' => $meth->getModifiers(), 'lineno' => 0, 'endLineno' => 0, 'name' => $method->name, 'docComment' => '', 'required' => $required, 'optional' => $optional, 'ret' => null]; $arginfo = null; if (!empty($internal_arginfo["{$class_name}::{$method->name}"])) { $arginfo = $internal_arginfo["{$class_name}::{$method->name}"]; $classes[$lc]['methods'][$lmname]['ret'] = $arginfo[0]; } foreach ($method->getParameters() as $param) { $flags = 0; if ($param->isPassedByReference()) { $flags |= \ast\flags\PARAM_REF; } if ($param->isVariadic()) { $flags |= \ast\flags\PARAM_VARIADIC; } $classes[$lc]['methods'][strtolower($method->name)]['params'][] = ['file' => 'internal', 'flags' => $flags, 'lineno' => 0, 'name' => $param->name, 'type' => empty($arginfo) ? null : next($arginfo), 'def' => null]; } } }
/** * {@inheritdoc} */ protected function addRepository(ContainerBuilder $container, MetadataInterface $metadata) { $repositoryClass = new Parameter('sylius.phpcr_odm.repository.class'); if ($metadata->hasClass('repository')) { $repositoryClass = $metadata->getClass('repository'); } $repositoryReflection = new \ReflectionClass($repositoryClass); $definition = new Definition($repositoryClass); $definition->setArguments([new Reference($metadata->getServiceId('manager')), $this->getClassMetadataDefinition($metadata)]); $definition->setLazy(!$repositoryReflection->isFinal()); if ($metadata->hasParameter('translation')) { $translationConfig = $metadata->getParameter('translation'); if (in_array(TranslatableRepositoryInterface::class, class_implements($repositoryClass))) { if (isset($translationConfig['fields'])) { $definition->addMethodCall('setTranslatableFields', [$translationConfig['fields']]); } } } $container->setDefinition($metadata->getServiceId('repository'), $definition); }
/** * Return an array of info about the class * * @return array */ protected function _getClass() { $class = ''; if ($this->_Reflection->isFinal()) { $class .= 'final '; } if ($this->_Reflection->isAbstract() && !$this->_Reflection->isInterface()) { $class .= 'abstract '; } if ($this->_Reflection->isInterface()) { $class .= 'interface '; } else { $class .= 'class '; } $class .= $this->class . ' '; if ($this->_Reflection->getParentClass()) { $class .= 'extends ' . $this->_Reflection->getParentClass()->getName(); } $interfaces = $this->_Reflection->getInterfaces(); $number = count($interfaces); if ($number > 0) { $implements = ''; foreach ($interfaces as $int) { $intName = $int->getName(); if ($intName == 'CakeEventListener') { continue; } $implements .= $int->getName() . ' '; } if (!empty($implements)) { $class .= ' implements ' . $implements; } } $file = $this->_File->read(); preg_match_all('/App::(uses|import)\\(.*\\);/i', $file, $out); $uses = !empty($out[0]) ? $out[0] : array(); return array('class' => $class, 'doc' => $this->_Reflection->getDocComment(), 'uses' => $uses); }
public function initController() { // 开始缓存 $cache = new Cache(); $cache->read(); $cmdq = $this->getConfigs('cmdq'); $ctl_cls = ucfirst($cmdq->c); try { $reflector = new \ReflectionClass(sprintf('\\app\\controllers\\%s\\%s', $cmdq->d, $ctl_cls)); } catch (\Exception $e) { $this->show_503("无法通过反射,获取类{$ctl_cls}!", '文件不存在'); } $args = []; if (!empty($cmdq->q)) { // 如果使用汇总压缩css,js,则不能用,分割参数 $args = $cmdq->c == 'min' ? [$cmdq->q] : explode(',', $cmdq->q); } $reflector->isFinal() || $this->show_503($reflector->getName() . '类修饰符必须是final', '类修饰符错误'); $cls = $reflector->newInstance(); is_subclass_of($cls, '\\es\\core\\Controller\\ControllerAbstract') || $this->show_503('控制器必须是\\es\\core\\Controller\\ControllerAbstract的子类', '非控制器实例类'); $hook = $this->getConfigs('hook'); $hook->afterController(); $rMethod = null; try { $rMethod = $reflector->getMethod($cmdq->m); } catch (\Exception $e) { $this->show_503("控制器{$cmdq->c}方法{$cmdq->m}不存在", '方法不存在'); } $this->disable_method($rMethod); $rMethod->invokeArgs($cls, $args); $hook->afterControllerMethod(); $cls->closeDB(); // 关闭数据库 $html = $cls->output->display(1); // 输出 $cache->save($html); $this->render($html); }
function classData(ReflectionClass $class) { // получаем объект типа ReflectionClass $details = ""; $name = $class->getName(); if ($class->isUserDefined()) { $details .= "{$name} -- класс определён пользователем<br>"; } if ($class->isInterface()) { $details .= "{$name} -- это интерфейс"; } if ($class->isAbstract()) { $details .= "{$name} -- это абстрактный класс"; } if ($class->isFinal()) { $details .= "{$name} -- это финальный класс"; } if ($class->isInstantiable()) { $details .= "{$name} -- можно создать экземпляр класса"; } else { $details .= "{$name} -- нельзя создать экземпляр класса"; } return $details; }
function add_class($class_name) { global $classes, $internal_arginfo, $internal_classvars; $lc = strtolower($class_name); $class = new \ReflectionClass($class_name); $flags = 0; if ($class->isFinal()) { $flags = \ast\flags\CLASS_FINAL; } else { if ($class->isInterface()) { $flags = \ast\flags\CLASS_INTERFACE; } else { if ($class->isTrait()) { $flags = \ast\flags\CLASS_TRAIT; } } } if ($class->isAbstract()) { $flags |= \ast\flags\CLASS_ABSTRACT; } $classes[$lc] = ['file' => 'internal', 'namespace' => $class->getNamespaceName(), 'conditional' => false, 'flags' => $flags, 'lineno' => 0, 'endLineno' => 0, 'name' => $class_name, 'docComment' => '', 'type' => '', 'traits' => []]; $parent = $class->getParentClass(); if (!$parent) { $classes[$lc]['parent'] = ''; } else { $classes[$lc]['parent'] = $parent->getName(); } foreach ($class->getDefaultProperties() as $name => $value) { $type = $internal_classvars[strtolower($class_name)]['properties'][$name] ?? type_map(gettype($value)); # echo "{$class_name}::{$name} = ($type) $value\n"; $prop = new \ReflectionProperty($class_name, $name); $classes[$lc]['properties'][strtolower($name)] = ['flags' => $prop->getModifiers(), 'name' => $name, 'lineno' => 0, 'type' => type_map(gettype($value))]; } $classes[$lc]['interfaces'] = $class->getInterfaceNames(); $classes[$lc]['traits'] = $class->getTraitNames(); $parents = []; $parent = $class->getParentClass(); if ($parent) { $temp = $class; while ($parent = $temp->getParentClass()) { $parents[] = $parent->getName(); $parents = array_merge($parents, $parent->getInterfaceNames()); $temp = $parent; } } $types = [$class_name]; $types = array_merge($types, $classes[$lc]['interfaces']); $types = array_merge($types, $parents); $classes[$lc]['type'] = implode('|', array_unique($types)); foreach ($class->getConstants() as $name => $value) { $classes[$lc]['constants'][$name] = ['name' => $name, 'lineno' => 0, 'type' => type_map(gettype($value))]; } foreach ($class->getMethods() as $method) { $meth = new \ReflectionMethod($class_name, $method->name); $required = $meth->getNumberOfRequiredParameters(); $optional = $meth->getNumberOfParameters() - $required; $lmname = strtolower($method->name); $classes[$lc]['methods'][$lmname] = ['file' => 'internal', 'namespace' => $class->getNamespaceName(), 'conditional' => false, 'flags' => $meth->getModifiers(), 'lineno' => 0, 'endLineno' => 0, 'name' => $method->name, 'docComment' => '', 'required' => $required, 'optional' => $optional, 'ret' => null]; $arginfo = []; unset(${"arginfo1"}); $alt = 1; if (!empty($internal_arginfo["{$class_name}::{$method->name}"])) { $arginfo = $internal_arginfo["{$class_name}::{$method->name}"]; $classes[$lc]['methods'][$lmname]['ret'] = $arginfo[0]; while (!empty($internal_arginfo["{$class_name}::{$method->name} {$alt}"])) { $classes[$lc]['methods']["{$lmname} {$alt}"] = $classes[$lc]['methods'][$lmname]; ${"arginfo{$alt}"} = $internal_arginfo["{$class_name}::{$method->name} {$alt}"]; unset(${"arginfo" . ($alt + 1)}); $classes[$lc]['methods']["{$lmname} {$alt}"]['ret'] = ${"arginfo{$alt}"}[0]; $alt++; } } else { if (!empty($parents)) { foreach ($parents as $parent_name) { if (!empty($internal_arginfo["{$parent_name}::{$method->name}"])) { $classes[$lc]['methods']["{$lmname} {$alt}"] = $classes[$lc]['methods'][$lmname]; $arginfo = $internal_arginfo["{$parent_name}::{$method->name}"]; $classes[$lc]['methods'][$lmname]['ret'] = $arginfo[0]; while (!empty($internal_arginfo["{$parent_name}::{$method->name} {$alt}"])) { ${"arginfo{$alt}"} = $internal_arginfo["{$parent_name}::{$method->name} {$alt}"]; unset(${"arginfo" . ($alt + 1)}); $classes[$lc]['methods']["{$lmname} {$alt}"]['ret'] = ${"arginfo{$alt}"}[0]; $alt++; } break; } } } } foreach ($method->getParameters() as $param) { $alt = 1; $flags = 0; if ($param->isPassedByReference()) { $flags |= \ast\flags\PARAM_REF; } if ($param->isVariadic()) { $flags |= \ast\flags\PARAM_VARIADIC; } $classes[$lc]['methods'][strtolower($method->name)]['params'][] = ['file' => 'internal', 'flags' => $flags, 'lineno' => 0, 'name' => $param->name, 'type' => empty($arginfo) ? null : next($arginfo), 'def' => null]; while (!empty(${"arginfo{$alt}"})) { $classes[$lc]['methods'][strtolower($method->name) . ' ' . $alt]['params'][] = ['file' => 'internal', 'flags' => $flags, 'lineno' => 0, 'name' => $param->name, 'type' => empty(${"arginfo{$alt}"}) ? null : next(${"arginfo{$alt}"}), 'def' => null]; $alt++; } } } }
/** * @dataProvider provideTestClasses */ public function testThatTestClassesAreAbstractOrFinal(\ReflectionClass $rc) { $this->assertTrue($rc->isAbstract() || $rc->isFinal(), sprintf('Test class %s should be abstract or final.', $rc->getName())); }
* * @return string */'); sort($classes); $indexClasses = array(); $indexInterfaces = array(); foreach ($classes as $className) { $realClassName = $className; $simpleClassName = str_replace("\\", "_", $className); $reflector = new ReflectionClass($className); $documentationData = array(); $typeClass = 'public'; if ($reflector->isAbstract() == true) { $typeClass = 'abstract'; } if ($reflector->isFinal() == true) { $typeClass = 'final'; } if ($reflector->isInterface() == true) { $typeClass = ''; } $documentationData = array('type' => $typeClass, 'description' => $realClassName, 'extends' => $reflector->getParentClass(), 'implements' => $reflector->getInterfaceNames(), 'constants' => $reflector->getConstants(), 'methods' => $reflector->getMethods()); if ($reflector->isInterface() == true) { $indexInterfaces[] = ' ' . $simpleClassName . PHP_EOL; } else { $indexClasses[] = ' ' . $simpleClassName . PHP_EOL; } $nsClassName = str_replace("\\", "\\\\", $className); if ($reflector->isInterface() == true) { $code = 'Interface **' . $nsClassName . '**' . PHP_EOL; $code .= str_repeat("=", strlen($code) - 1) . PHP_EOL . PHP_EOL;
<?php function derp() { class HerpDerp extends Generator { } } $rc = new ReflectionClass('Generator'); var_dump($rc->isFinal()); derp();
protected function parse_class($class) { // Use reflection to find information $reflection = new ReflectionClass($class); // Class definition $class = array('name' => $reflection->getName(), 'comment' => $this->parse_comment($reflection->getDocComment()), 'final' => $reflection->isFinal(), 'abstract' => $reflection->isAbstract(), 'interface' => $reflection->isInterface(), 'extends' => '', 'implements' => array(), 'methods' => array()); if ($implements = $reflection->getInterfaces()) { foreach ($implements as $interface) { // Get implemented interfaces $class['implements'][] = $interface->getName(); } } if ($parent = $reflection->getParentClass()) { // Get parent class $class['extends'] = $parent->getName(); } if ($methods = $reflection->getMethods()) { foreach ($methods as $method) { // Don't try to document internal methods if ($method->isInternal()) { continue; } $class['methods'][] = array('name' => $method->getName(), 'comment' => $this->parse_comment($method->getDocComment()), 'class' => $class['name'], 'final' => $method->isFinal(), 'static' => $method->isStatic(), 'abstract' => $method->isAbstract(), 'visibility' => $this->visibility($method), 'parameters' => $this->parameters($method)); } } return $class; }
/** * @return MetaConfiguration **/ private function checkClassSanity(MetaClass $class, ReflectionClass $info) { switch ($class->getTypeId()) { case null: break; case MetaClassType::CLASS_ABSTRACT: Assert::isTrue($info->isAbstract(), 'class ' . $info->getName() . ' expected to be abstract'); Assert::isTrue($class->getPattern() instanceof AbstractClassPattern, 'class ' . $info->getName() . ' must use AbstractClassPattern'); break; case MetaClassType::CLASS_FINAL: Assert::isTrue($info->isFinal(), 'class ' . $info->getName() . ' expected to be final'); break; case MetaClassType::CLASS_SPOOKED: default: Assert::isUnreachable(); break; } if ($public = $info->getProperties(ReflectionProperty::IS_PUBLIC)) { Assert::isUnreachable($class->getName() . ' contains properties with evil visibility:' . "\n" . print_r($public, true)); } return $this; }
/** * @param CodeBase $code_base * A reference to the entire code base in which this * context exists * * @param ReflectionClass $class * A reflection class representing a builtin class. * * @return Clazz * A Class structural element representing the given named * builtin. */ public static function fromReflectionClass(CodeBase $code_base, \ReflectionClass $class) : Clazz { // Build a set of flags based on the constitution // of the built-in class $flags = 0; if ($class->isFinal()) { $flags = \ast\flags\CLASS_FINAL; } else { if ($class->isInterface()) { $flags = \ast\flags\CLASS_INTERFACE; } else { if ($class->isTrait()) { $flags = \ast\flags\CLASS_TRAIT; } } } if ($class->isAbstract()) { $flags |= \ast\flags\CLASS_ABSTRACT; } $context = new Context(); // Build a base class element $clazz = new Clazz($context, $class->getName(), UnionType::fromStringInContext($class->getName(), $context), $flags); // If this class has a parent class, add it to the // class info if ($parent_class = $class->getParentClass()) { $parent_class_fqsen = FullyQualifiedClassName::fromFullyQualifiedString('\\' . $parent_class->getName()); $clazz->setParentClassFQSEN($parent_class_fqsen); } foreach ($class->getDefaultProperties() as $name => $value) { // TODO: whats going on here? $reflection_property = new \ReflectionProperty($class->getName(), $name); $property = new Property($context->withClassFQSEN($clazz->getFQSEN()), $name, Type::fromObject($value)->asUnionType(), 0); $clazz->addProperty($code_base, $property); } foreach ($class->getInterfaceNames() as $name) { $clazz->addInterfaceClassFQSEN(FullyQualifiedClassName::fromFullyQualifiedString('\\' . $name)); } foreach ($class->getTraitNames() as $name) { $clazz->addTraitFQSEN(FullyQualifiedClassName::fromFullyQualifiedString('\\' . $name)); } foreach ($class->getConstants() as $name => $value) { $clazz->addConstant($code_base, new Constant($context, $name, Type::fromObject($value)->asUnionType(), 0)); } foreach ($class->getMethods() as $reflection_method) { $method_list = Method::methodListFromReflectionClassAndMethod($context->withClassFQSEN($clazz->getFQSEN()), $code_base, $class, $reflection_method); foreach ($method_list as $method) { $clazz->addMethod($code_base, $method); } } return $clazz; }
protected function assertNotFinal(ReflectionClass $c) { if ($c->isFinal()) { throw new FBMock_TestDoubleException("Cannot mock final class %s", $c->getName()); } }