Inheritance: implements BetterReflection\Reflector\Reflector
 public function testFromTrait()
 {
     $sourceLocator = new SingleFileSourceLocator(__DIR__ . '/../../Fixture/ExampleClass.php');
     $reflector = new ClassReflector($sourceLocator);
     $exception = NotAClassReflection::fromReflectionClass($reflector->reflect(Fixture\ExampleTrait::class));
     $this->assertInstanceOf(NotAClassReflection::class, $exception);
     $this->assertSame('Provided node "' . Fixture\ExampleTrait::class . '" is not class, but "trait"', $exception->getMessage());
 }
 public function testCreatingContextWithSelf()
 {
     $reflector = new ClassReflector(new StringSourceLocator('<?php class Foo {}'));
     $self = $reflector->reflect('Foo');
     $context = new CompilerContext($reflector, $self);
     $this->assertTrue($context->hasSelf());
     $this->assertSame($reflector, $context->getReflector());
     $this->assertSame($self, $context->getSelf());
 }
 public function reflectClass(string $className) : ClassReflection
 {
     try {
         $reflection = $this->classReflector->reflect($className);
         return new BetterReflectionClassReflection($reflection, $this->annotationsScanner, $this, $this->typeFactory, $reflection->getFileName() ? $this->importScanner->scanForImports($reflection->getFileName()) : []);
     } catch (IdentifierNotFound $exception) {
         throw ClassNotFound::named($className);
     }
 }
 public function testClassLoadsWorksWithExistingClass()
 {
     $reflector = new ClassReflector(new AutoloadSourceLocator());
     // Ensure class is loaded first
     new ClassForHinting();
     $className = 'BetterReflectionTest\\Fixture\\ClassForHinting';
     $this->assertTrue(class_exists($className, false));
     $classInfo = $reflector->reflect($className);
     $this->assertSame('ClassForHinting', $classInfo->getShortName());
 }
 public function testCanReflectEvaledLocatedSourceClass()
 {
     /* @var $class */
     $reflector = new ClassReflector(new EvaledCodeSourceLocator());
     $className = uniqid('foo');
     eval('class ' . $className . ' {function foo($bar = "baz") {}}');
     $class = $reflector->reflect($className);
     $this->assertInstanceOf(ReflectionClass::class, $class);
     $this->assertSame($className, $class->getName());
     $this->assertFalse($class->isInternal());
     $this->assertTrue($class->isUserDefined());
     $this->assertNull($class->getFileName());
     $this->assertCount(1, $class->getMethods());
 }
 /**
  * @dataProvider internalSymbolsProvider
  *
  * @param string $className
  */
 public function testCanReflectInternalClasses($className)
 {
     /* @var $class */
     $reflector = new ClassReflector(new PhpInternalSourceLocator());
     try {
         $class = $reflector->reflect($className);
     } catch (\ReflectionException $e) {
         $this->markTestIncomplete(sprintf('Can\'t reflect class "%s" due to an internal reflection exception: "%s". Consider adding a stub class', $className, $e->getMessage()));
     }
     $this->assertInstanceOf(ReflectionClass::class, $class);
     $this->assertSame($className, $class->getName());
     $this->assertTrue($class->isInternal());
     $this->assertFalse($class->isUserDefined());
 }
 public function testCannotClone()
 {
     $classInfo = $this->reflector->reflect('\\BetterReflectionTest\\Fixture\\ExampleClass');
     $publicProp = $classInfo->getProperty('publicProperty');
     $this->setExpectedException(Uncloneable::class);
     $unused = clone $publicProp;
 }
 public function testSetVisibilityThrowsExceptionWithInvalidArgument()
 {
     $classInfo = $this->reflector->reflect('\\BetterReflectionTest\\Fixture\\ExampleClass');
     $publicProp = $classInfo->getProperty('publicProperty');
     $this->expectException(\InvalidArgumentException::class);
     $this->expectExceptionMessage('Visibility should be \\ReflectionProperty::IS_PRIVATE, ::IS_PROTECTED or ::IS_PUBLIC constants');
     $publicProp->setVisibility('foo');
 }
 public function testCannotClone()
 {
     $classInfo = $this->reflector->reflect('\\BetterReflectionTest\\Fixture\\Methods');
     $methodInfo = $classInfo->getMethod('methodWithParameters');
     $paramInfo = $methodInfo->getParameter('parameter1');
     $this->expectException(Uncloneable::class);
     $unused = clone $paramInfo;
 }
 public function testMethodNameWithNamespace()
 {
     $classInfo = $this->reflector->reflect('\\BetterReflectionTest\\Fixture\\ExampleClass');
     $methodInfo = $classInfo->getMethod('someMethod');
     $this->assertFalse($methodInfo->inNamespace());
     $this->assertSame('someMethod', $methodInfo->getName());
     $this->assertSame('', $methodInfo->getNamespaceName());
     $this->assertSame('someMethod', $methodInfo->getShortName());
 }
 /**
  * Pass an instance of an object to this method to reflect it
  *
  * @param object $object
  * @return ReflectionClass
  */
 public static function createFromInstance($object)
 {
     if (gettype($object) !== 'object') {
         throw new \InvalidArgumentException('Can only create from an instance of an object');
     }
     $reflector = ClassReflector::buildDefaultReflector();
     $reflectionClass = $reflector->reflect(get_class($object));
     return new self($reflector, $reflectionClass, $object);
 }
 public function testIsDefaultValueConstantAndGetDefaultValueConstantName()
 {
     $classInfo = $this->reflector->reflect('\\BetterReflectionTest\\Fixture\\Methods');
     $method = $classInfo->getMethod('methodWithConstAsDefault');
     $intDefault = $method->getParameter('intDefault');
     $this->assertFalse($intDefault->isDefaultValueConstant());
     $constDefault = $method->getParameter('constDefault');
     $this->assertTrue($constDefault->isDefaultValueConstant());
     $this->assertSame('SOME_CONST', $constDefault->getDefaultValueConstantName());
     $definedDefault = $method->getParameter('definedDefault');
     $this->assertTrue($definedDefault->isDefaultValueConstant());
     $this->assertSame('SOME_DEFINED_VALUE', $definedDefault->getDefaultValueConstantName());
 }
 /**
  * @param string $propertyName
  * @param string $expectedString
  * @dataProvider castToStringProvider
  */
 public function testCastingToString($propertyName, $expectedString)
 {
     $classInfo = $this->reflector->reflect('\\BetterReflectionTest\\Fixture\\ExampleClass');
     $this->assertSame($expectedString, (string) $classInfo->getProperty($propertyName));
 }
 public function testGetImmediateInterfaces()
 {
     $reflector = new ClassReflector(new SingleFileSourceLocator(__DIR__ . '/../Fixture/PrototypeTree.php'));
     $interfaces = $reflector->reflect('Boom\\B')->getImmediateInterfaces();
     $this->assertCount(1, $interfaces);
     $this->assertInstanceOf(ReflectionClass::class, $interfaces['Boom\\Bar']);
     $this->assertSame('Boom\\Bar', $interfaces['Boom\\Bar']->getName());
 }
function analyzeCodeInPath($srcPath)
{
    $objects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($srcPath), \RecursiveIteratorIterator::SELF_FIRST);
    $extensions = ['php', 'php5', 'phtml', 'inc', 'module', 'install'];
    $regexString = '#.*\\.(' . implode('|', $extensions) . ')#';
    $templateObjects = new \RegexIterator($objects, $regexString);
    $sourceFiles = [];
    foreach ($templateObjects as $key => $var) {
        $sourceFiles[] = $var;
    }
    try {
        foreach ($sourceFiles as $sourceFile) {
            $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
            try {
                $code = @file_get_contents($sourceFile);
                if ($code === false) {
                    echo "Failed to get contents of {$sourceFile} \n";
                    continue;
                }
                $nodes = $parser->parse($code);
                if ($code === null) {
                    echo "Failed to parse code for file {$sourceFile}";
                    continue;
                }
                $classes = parseNodes($nodes);
                $sourceLocator = new SingleFileSourceLocator($sourceFile);
                $reflector = new ClassReflector($sourceLocator);
                foreach ($classes as $class) {
                    echo "Attempting to analyze class [{$class}]\n";
                    $reflClass = $reflector->reflect($class);
                    if ($reflClass == null) {
                        echo "Failed to reflect class [{$reflClass}]";
                        break 2;
                    }
                    $properties = $reflClass->getProperties();
                    $methods = $reflClass->getMethods();
                    $clashingProperties = [];
                    foreach ($properties as $property) {
                        foreach ($methods as $method) {
                            if (strcasecmp($property->getName(), $method->getName()) === 0) {
                                $clashingProperties[] = $property->getName();
                            }
                        }
                    }
                    if (count($clashingProperties) == 0) {
                        echo "Class [{$class}] has no clashing properties\n";
                    } else {
                        echo "Class [{$class}] has the following clashing properties\n";
                        foreach ($clashingProperties as $clashingProperty) {
                            echo "    {$clashingProperty}\n";
                        }
                    }
                }
            } catch (PhpParser\Error $e) {
                echo "Failed to parse code\n";
            }
        }
    } catch (\Throwable $t) {
        echo "Code analysis failed.'\n";
        echo get_class($t) . " : " . $t->getMessage() . "\n";
        echo $t->getTraceAsString();
    }
}
 /**
  * @dataProvider stubbedClassesProvider
  *
  * @param string $className
  *
  * @coversNothing
  */
 public function testAllGeneratedStubsAreInSyncWithInternalReflectionClasses($className)
 {
     if (!(class_exists($className, false) || interface_exists($className, false) || trait_exists($className, false))) {
         $this->markTestSkipped(sprintf('Class "%s" is not available in this environment', $className));
     }
     $reflector = new ClassReflector(new PhpInternalSourceLocator());
     $this->assertSameClassAttributes(new \ReflectionClass($className), $reflector->reflect($className));
 }
 public function testReturnsNullWhenUnableToAutoload()
 {
     $reflector = new ClassReflector(new AutoloadSourceLocator());
     $this->assertNull($reflector->reflect('Some\\Class\\That\\Cannot\\Exist'));
 }
 /**
  * @param string $methodName
  * @param string $expectedStringValue
  * @dataProvider methodStringRepresentations
  */
 public function testStringCast($methodName, $expectedStringValue)
 {
     $classInfo = $this->reflector->reflect('\\BetterReflectionTest\\Fixture\\Methods');
     $method = $classInfo->getMethod($methodName);
     $this->assertStringMatchesFormat($expectedStringValue, (string) $method);
 }
 /**
  * @param string $propertyName
  * @param string[] $expectedTypes
  * @dataProvider typesDataProvider
  */
 public function testGetDocBlockTypeStrings($propertyName, $expectedTypes)
 {
     $classInfo = $this->reflector->reflect('\\BetterReflectionTest\\Fixture\\ExampleClass');
     $property = $classInfo->getProperty($propertyName);
     $this->assertSame($expectedTypes, $property->getDocBlockTypeStrings());
 }
 public function testCannotClone()
 {
     $reflector = new ClassReflector($this->getComposerLocator());
     $classInfo = $reflector->reflect('\\BetterReflectionTest\\Fixture\\ExampleClass');
     $this->setExpectedException(Uncloneable::class);
     $unused = clone $classInfo;
 }
 public function testGetDeclaringClassForMethod()
 {
     $content = "<?php class Foo { public function myMethod(\$var = 123) {} }";
     $reflector = new ClassReflector(new StringSourceLocator($content));
     $classInfo = $reflector->reflect('Foo');
     $methodInfo = $classInfo->getMethod('myMethod');
     $paramInfo = $methodInfo->getParameter('var');
     $this->assertSame($classInfo, $paramInfo->getDeclaringClass());
 }
 /**
  * @param string $class
  * @param string $method
  * @param string|null $expectedPrototype
  * @dataProvider prototypeProvider
  */
 public function testGetPrototype($class, $method, $expectedPrototype)
 {
     $fixture = __DIR__ . '/../Fixture/PrototypeTree.php';
     $reflector = new ClassReflector(new SingleFileSourceLocator($fixture));
     if (null === $expectedPrototype) {
         $this->setExpectedException(MethodPrototypeNotFound::class);
     }
     $b = $reflector->reflect($class)->getMethod($method)->getPrototype();
     $this->assertInstanceOf(ReflectionMethod::class, $b);
     $this->assertSame($expectedPrototype, $b->getDeclaringClass()->getName());
 }
 /**
  * Create a ReflectionFunction for the specified $functionName.
  *
  * @param string $functionName
  * @return \BetterReflection\Reflection\ReflectionFunction
  */
 public function reflect($functionName)
 {
     return $this->sourceLocator->locateIdentifier(ClassReflector::buildDefaultReflector(), new Identifier($functionName, new IdentifierType(IdentifierType::IDENTIFIER_FUNCTION)));
 }
 public function testExceptionThrownWhenUnableToAutoload()
 {
     $reflector = new ClassReflector(new AutoloadSourceLocator());
     $this->setExpectedException(IdentifierNotFound::class);
     $reflector->reflect('Some\\Class\\That\\Cannot\\Exist');
 }
 public function testGetFileName()
 {
     $reflector = new ClassReflector($this->getComposerLocator());
     $classInfo = $reflector->reflect('\\BetterReflectionTest\\Fixture\\ExampleClass');
     $detectedFilename = $classInfo->getFileName();
     $this->assertSame('ExampleClass.php', basename($detectedFilename));
 }
<?php

// Loading a specific file (not from autoloader)
require_once __DIR__ . '/../../vendor/autoload.php';
use BetterReflection\Reflector\ClassReflector;
use BetterReflection\SourceLocator\Type\AggregateSourceLocator;
use BetterReflection\SourceLocator\Type\SingleFileSourceLocator;
$reflector = new ClassReflector(new AggregateSourceLocator([new SingleFileSourceLocator('assets/MyClass.php')]));
$reflection = $reflector->reflect('MyClass');
var_dump($reflection->getName());
// MyClass
var_dump($reflection->getProperty('foo')->isPrivate());
// true
var_dump($reflection->getProperty('foo')->getDocBlockTypeStrings()[0]);
// string
var_dump($reflection->getMethod('getFoo')->getDocBlockReturnTypes()[0]->__toString());
// string
 /**
  * Create a ReflectionClass by name, using default reflectors etc.
  *
  * @param string $className
  * @return ReflectionClass
  */
 public static function createFromName($className)
 {
     return ClassReflector::buildDefaultReflector()->reflect($className);
 }
 public function testImplementsReflector()
 {
     $php = '<?php class Foo {}';
     $reflector = new ClassReflector(new StringSourceLocator($php));
     $classInfo = $reflector->reflect('Foo');
     $this->assertInstanceOf(\Reflector::class, $classInfo);
 }
 public function testClassConstantResolutionStaticForMethod()
 {
     $phpCode = '<?php
     class Foo {
         const BAR = "baz";
         public function method($param = static::BAR) {}
     }
     ';
     $reflector = new ClassReflector(new StringSourceLocator($phpCode));
     $classInfo = $reflector->reflect('Foo');
     $methodInfo = $classInfo->getMethod('method');
     $paramInfo = $methodInfo->getParameter('param');
     $this->assertSame('baz', $paramInfo->getDefaultValue());
 }
Beispiel #30
0
 /**
  * @param \nochso\WriteMe\Document $document
  *
  * @return \BetterReflection\Reflection\ReflectionClass[]
  */
 private function getClasses(Document $document)
 {
     $files = $this->getFiles($document);
     $singleLocators = [];
     foreach ($files as $file) {
         $singleLocators[] = new SingleFileSourceLocator($file->getPathname());
     }
     $reflector = new ClassReflector(new AggregateSourceLocator($singleLocators));
     $classes = $reflector->getAllClasses();
     usort($classes, function (ReflectionClass $a, ReflectionClass $b) {
         $ans = $a->getNamespaceName();
         $bns = $b->getNamespaceName();
         if ($ans === $bns) {
             return strnatcmp($a->getShortName(), $b->getShortName());
         }
         return strnatcmp($ans, $bns);
     });
     return $classes;
 }