public function getStaticProperty($class, $property) { $refl = new \reflectionClass($class); // Check that property is static AND public if ($refl->hasProperty($property) && $refl->getProperty($property)->isStatic() && $refl->getProperty($property)->isPublic()) { return $refl->getProperty($property)->getValue(); } throw new \RuntimeException(sprintf('Invalid static property get for class %s and property %s', $class, $property)); }
function reflectMethodModifiers($class) { $classInfo = new reflectionClass($class); $methodArray = $classInfo->getMethods(); foreach ($methodArray as $method) { echo "Modifiers for method {$method->class}::{$method->name}():\n"; printf("0x%08x\n", $method->getModifiers()); echo "\n\n"; } }
private function addToPool($entity) { $reflection = new reflectionClass($entity); $class = $reflection->getShortName(); if (!$this->collectionExist($class)) { static::$pool[$class] = new Collection(); } static::$pool[$class]->push($entity->id); return $entity; }
/** * Haalt alle geladen classes op die 'custom zijn. * * @return IPReflectionClass[] */ public function getClasses() { $ar = get_declared_classes(); foreach ($ar as $class) { $c = new reflectionClass($class); if ($c->isUserDefined()) { //add only when class is user-defined $this->classes[$class] = new IPReflectionClass($class); } } ksort($this->classes); return $this->classes; }
protected static function canInstanciateClass($class) { $reflection = new \reflectionClass($class); if ($reflection->hasMethod('__construct') === false) { return true; } $constructor = $reflection->getMethod('__construct'); if ($constructor->isPublic() === false) { throw new provider\object\exceptions\privateConstructor('Could not instanciate an object from ' . $class . ' because ' . $class . '::__construct() is private'); } if ($constructor->getNumberOfRequiredParameters() > 0) { throw new provider\object\exceptions\mandatoryArgument('Could not instanciate an object from ' . $class . ' because ' . $class . '::__construct() has at least one mandatory argument'); } return true; }
public function __toString() { $string = ''; if (sizeof($this->coverage) > 0) { try { $nodes = array('coverage' => round($this->coverage->getValue() * 100, 2), 'project' => $this->projectName, 'name' => '', 'fullname' => '', 'htmlReportBaseUrl' => $this->htmlReportBaseUrl, 'date' => time(), 'children' => array()); foreach ($this->coverage->getClasses() as $className => $classPath) { $node =& $nodes; $class = new \reflectionClass($className); $namespaces = explode('\\', $class->getNamespaceName()); foreach ($namespaces as $namespace) { $childFound = false; foreach ($node['children'] as $key => $child) { $childFound = $child['name'] === $namespace; if ($childFound === true) { break; } } if ($childFound === false) { $key = sizeof($node['children']); $node['children'][] = array('name' => $namespace, 'fullname' => $node['fullname'] . ($node['fullname'] == '' ? '' : '\\') . $namespace, 'children' => array()); } $node =& $node['children'][$key]; } $child = array('name' => $class->getShortName(), 'fullname' => $node['fullname'] . '\\' . $class->getShortName(), 'covered' => $this->coverage->getNumberOfCoveredLinesInClass($className), 'coverable' => $this->coverage->getNumberOfCoverableLinesInClass($className), 'pourcent' => round($this->coverage->getValueForClass($className) * 100, 2), 'children' => array()); $node['children'][] = $child; } if (@file_put_contents($this->destinationDirectory . DIRECTORY_SEPARATOR . self::dataFile, json_encode($nodes)) === false) { throw new exceptions\runtime($this->locale->_('Unable to write in \'' . $this->destinationDirectory . '\'')); } try { $resourcesDirectoryIterator = new \recursiveIteratorIterator(new atoum\iterators\filters\recursives\dot($this->resourcesDirectory)); } catch (\exception $exception) { throw new exceptions\runtime($this->locale->_('Directory \'' . $this->resourcesDirectory . '\' does not exist')); } foreach ($resourcesDirectoryIterator as $file) { if (@copy($file, $this->destinationDirectory . DIRECTORY_SEPARATOR . $resourcesDirectoryIterator->getSubPathname()) === false) { throw new exceptions\runtime($this->locale->_('Unable to write in \'' . $this->destinationDirectory . '\'')); } } $string .= $this->urlPrompt . $this->urlColorizer->colorize(sprintf($this->locale->_('Treemap of code coverage are available at %s.'), $this->treemapUrl)) . PHP_EOL; } catch (\exception $exception) { $string .= $this->urlPrompt . $this->urlColorizer->colorize(sprintf($this->locale->_('Unable to generate code coverage at %s: %s.'), $this->treemapUrl, $exception->getMessage())) . PHP_EOL; } } return $string; }
/** * Levert een array met variabelen van deze class op * * @param boolean If the method should also return protected properties * @param boolean If the method should also return private properties * @return IPReflectionProperty[] */ public function getProperties($alsoProtected = true, $alsoPrivate = true) { $ar = parent::getProperties(); $this->properties = array(); foreach ($ar as $property) { if ((!$property->isPrivate() || $alsoPrivate) && (!$property->isProtected() || $alsoProtected)) { try { $p = new IPReflectionProperty($this->classname, $property->getName()); $this->properties[$property->name] = $p; } catch (ReflectionException $exception) { echo "Fout bij property: " . $property->name . "<br>\n"; } } } ksort($this->properties); return $this->properties; }
public function build(\reflectionClass $class, &$instance = null) { $this->factory = null; if ($class->isInterface() === false && $class->isAbstract() === false) { $constructor = $class->getConstructor(); if ($constructor === null || $constructor->isPublic() === true) { $constructorParameters = $closureParameters = array(); if ($constructor !== null) { $this->allArgumentsAreOptional = $constructor->getNumberOfRequiredParameters() === 0; foreach ($constructor->getParameters() as $position => $parameter) { $closureParameters[$position] = ($parameter->isPassedByReference() === false ? '' : '& ') . ($constructorParameters[$position] = '$' . $parameter->getName()); if (self::isVariadic($parameter)) { $closureParameters[$position] = '...' . $closureParameters[$position]; $constructorParameters[$position] = '...' . $constructorParameters[$position]; } switch (true) { case $parameter->isDefaultValueAvailable(): $defaultValue = var_export($parameter->getDefaultValue(), true); break; case $parameter->isOptional() && self::isVariadic($parameter) === false: $defaultValue = 'null'; break; default: $defaultValue = null; } if ($defaultValue !== null) { $closureParameters[$position] .= ' = ' . $defaultValue; } } } if ($constructor === null || sizeof($closureParameters) <= 0) { $this->factory = function () use(&$instance, $class) { return $instance = $class->newInstanceArgs(func_get_args()); }; } else { $this->factory = eval('return function(' . join(', ', $closureParameters) . ') use (& $instance) { return ($instance = new ' . $class->getName() . '(' . join(', ', $constructorParameters) . ')); };'); } } } return $this; }
protected function generateInterfaceCode(\reflectionClass $class, $mockNamespace, $mockClass) { $addIteratorAggregate = $class->isInstantiable() === false && ($class->implementsInterface('traversable') === true && $class->implementsInterface('iterator') === false && $class->implementsInterface('iteratorAggregate') === false); return 'namespace ' . ltrim($mockNamespace, '\\') . ' {' . PHP_EOL . 'final class ' . $mockClass . ' implements \\' . ($addIteratorAggregate === false ? '' : 'iteratorAggregate, \\') . $class->getName() . ', \\' . __NAMESPACE__ . '\\aggregator' . PHP_EOL . '{' . PHP_EOL . self::generateMockControllerMethods() . $this->generateInterfaceMethodCode($class, $addIteratorAggregate) . '}' . PHP_EOL . '}'; }
/** * Get the response instance * * @return mr_server_response_abstract */ protected function get_response() { if (!$this->response instanceof mr_server_response_abstract) { $reflection = new reflectionClass($this->responseclass); $this->response = $reflection->newInstance($this, $this->serviceclass); } return $this->response; }
public function runTestMethod($testMethod, array $tags = array()) { if ($this->methodIsIgnored($testMethod, $tags) === false) { $this->mockAutoloader->setMockGenerator($this->mockGenerator)->register(); set_error_handler(array($this, 'errorHandler')); ini_set('display_errors', 'stderr'); ini_set('log_errors', 'Off'); ini_set('log_errors_max_len', '0'); $this->currentMethod = $testMethod; $this->executeOnFailure = array(); $this->phpMocker->setDefaultNamespace($this->getTestedClassNamespace()); try { foreach ($this->getMethodPhpVersions($testMethod) as $phpVersion => $operator) { if (version_compare(phpversion(), $phpVersion, $operator) === false) { throw new test\exceptions\skip('PHP version ' . PHP_VERSION . ' is not ' . $operator . ' to ' . $phpVersion); } } foreach ($this->getMandatoryMethodExtensions($testMethod) as $mandatoryExtension) { try { call_user_func($this->phpExtensionFactory, $mandatoryExtension)->requireExtension(); } catch (atoum\php\exception $exception) { throw new test\exceptions\skip($exception->getMessage()); } } try { ob_start(); test\adapter::setStorage($this->testAdapterStorage); mock\controller::setLinker($this->mockControllerLinker); $this->testAdapterStorage->add(php\mocker::getAdapter()); $this->beforeTestMethod($this->currentMethod); $this->mockGenerator->testedClassIs($this->getTestedClassName()); try { $testedClass = new \reflectionClass($testedClassName = $this->getTestedClassName()); } catch (\exception $exception) { throw new exceptions\runtime('Tested class \'' . $testedClassName . '\' does not exist for test class \'' . $this->getClass() . '\''); } if ($testedClass->isAbstract() === true) { $testedClass = new \reflectionClass($testedClassName = $this->mockGenerator->getDefaultNamespace() . '\\' . $testedClassName); } $this->factoryBuilder->build($testedClass, $instance)->addToAssertionManager($this->assertionManager, 'newTestedInstance', function () use($testedClass) { throw new exceptions\runtime('Tested class ' . $testedClass->getName() . ' has no constructor or its constructor has at least one mandatory argument'); }); $this->factoryBuilder->build($testedClass)->addToAssertionManager($this->assertionManager, 'newInstance', function () use($testedClass) { throw new exceptions\runtime('Tested class ' . $testedClass->getName() . ' has no constructor or its constructor has at least one mandatory argument'); }); $this->assertionManager->setPropertyHandler('testedInstance', function () use(&$instance) { if ($instance === null) { throw new exceptions\runtime('Use $this->newTestedInstance before using $this->testedInstance'); } return $instance; }); if ($this->codeCoverageIsEnabled() === true) { $options = XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE; if ($this->branchesAndPathsCoverageIsEnabled() === true) { $options |= XDEBUG_CC_BRANCH_CHECK; } xdebug_start_code_coverage($options); } $assertionNumber = $this->score->getAssertionNumber(); $time = microtime(true); $memory = memory_get_usage(true); if (isset($this->dataProviders[$testMethod]) === false) { $this->{$testMethod}(); $this->asserterCallManager->check(); } else { $data = $this->{$this->dataProviders[$testMethod]}(); if (is_array($data) === false && $data instanceof \traversable === false) { throw new test\exceptions\runtime('Data provider ' . $this->getClass() . '::' . $this->dataProviders[$testMethod] . '() must return an array or an iterator'); } $reflectedTestMethod = call_user_func($this->reflectionMethodFactory, $this, $testMethod); $numberOfArguments = $reflectedTestMethod->getNumberOfRequiredParameters(); foreach ($data as $key => $arguments) { if (is_array($arguments) === false) { $arguments = array($arguments); } if (sizeof($arguments) != $numberOfArguments) { throw new test\exceptions\runtime('Data provider ' . $this->getClass() . '::' . $this->dataProviders[$testMethod] . '() not provide enough arguments at key ' . $key . ' for test method ' . $this->getClass() . '::' . $testMethod . '()'); } $this->score->setDataSet($key, $this->dataProviders[$testMethod]); $reflectedTestMethod->invokeArgs($this, $arguments); $this->asserterCallManager->check(); $this->score->unsetDataSet(); } } $this->mockControllerLinker->reset(); $this->testAdapterStorage->reset(); $memoryUsage = memory_get_usage(true) - $memory; $duration = microtime(true) - $time; $this->score->addMemoryUsage($this->path, $this->class, $this->currentMethod, $memoryUsage)->addDuration($this->path, $this->class, $this->currentMethod, $duration)->addOutput($this->path, $this->class, $this->currentMethod, ob_get_clean()); if ($this->codeCoverageIsEnabled() === true) { $this->score->getCoverage()->addXdebugDataForTest($this, xdebug_get_code_coverage()); xdebug_stop_code_coverage(); } if ($assertionNumber == $this->score->getAssertionNumber() && $this->methodIsNotVoid($this->currentMethod) === false) { $this->score->addVoidMethod($this->path, $this->class, $this->currentMethod); } } catch (\exception $exception) { $this->score->addOutput($this->path, $this->class, $this->currentMethod, ob_get_clean()); throw $exception; } } catch (asserter\exception $exception) { foreach ($this->executeOnFailure as $closure) { ob_start(); $closure(); $this->score->addOutput($this->path, $this->class, $this->currentMethod, ob_get_clean()); } if ($this->score->failExists($exception) === false) { $this->addExceptionToScore($exception); } } catch (test\exceptions\runtime $exception) { $this->score->addRuntimeException($this->path, $this->class, $this->currentMethod, $exception); } catch (test\exceptions\skip $exception) { list($file, $line) = $this->getBacktrace($exception->getTrace()); $this->score->addSkippedMethod($file, $this->class, $this->currentMethod, $line, $exception->getMessage()); } catch (test\exceptions\stop $exception) { } catch (exception $exception) { list($file, $line) = $this->getBacktrace($exception->getTrace()); $this->errorHandler(E_USER_ERROR, $exception->getMessage(), $file, $line); } catch (\exception $exception) { $this->addExceptionToScore($exception); } $this->afterTestMethod($this->currentMethod); $this->currentMethod = null; restore_error_handler(); ini_restore('display_errors'); ini_restore('log_errors'); ini_restore('log_errors_max_len'); $this->mockAutoloader->unregister(); } return $this; }
<pre> <?php include './validator.inc'; // print reflection reflectionClass::export('validator'); echo '</pre>'; //print source code highlight_file('./validator.inc');
public function generate($testClassPath) { if ($this->testedClassesDirectory === null) { throw new generator\exception('Tested classes directory is undefined'); } if ($this->testClassesDirectory === null) { throw new generator\exception('Tests directory is undefined'); } if ($this->testedClassNamespace === null) { throw new generator\exception('Tested class namespace is undefined'); } if ($this->testClassNamespace === null) { throw new generator\exception('Test class namespace is undefined'); } $testClassesDirectory = $this->pathFactory->build($this->testClassesDirectory); if ($testClassesDirectory->exists() === false) { throw new generator\exception('Test classes directory \'' . $testClassesDirectory . '\' does not exist'); } $realTestClassesDirectory = $testClassesDirectory->getRealPath(); $realTestClassPath = $this->pathFactory->build($testClassPath)->getRealPath(); $realTestClassBaseDirectory = $realTestClassPath->getRealParentDirectoryPath(); if ((string) $realTestClassesDirectory !== (string) $realTestClassBaseDirectory && $realTestClassBaseDirectory->isSubPathOf($realTestClassesDirectory) === false) { throw new generator\exception('Path \'' . $testClassPath . '\' is not in directory \'' . $this->testClassesDirectory . '\''); } $realTestClassRelativePath = substr($realTestClassPath->getRelativePathFrom($realTestClassesDirectory), 2); $fullyQualifiedTestClassName = call_user_func_array($this->fullyQualifiedTestClassNameExtractor, array($this, $realTestClassRelativePath)); $testClassTemplate = $this->templateParser->parseFile($this->templatesDirectory . DIRECTORY_SEPARATOR . 'testClass.php'); $testClassTemplate->fullyQualifiedTestClassName = $fullyQualifiedTestClassName; $testClassTemplate->testClassName = self::getShortClassName($fullyQualifiedTestClassName); $testClassTemplate->testClassNamespace = self::getClassNamespace($fullyQualifiedTestClassName); if ($this->runnerPath !== null) { $runnerPath = $this->pathFactory->build($this->runnerPath); $relativeRunnerPath = $runnerPath->relativizeFrom($realTestClassBaseDirectory); $testClassTemplate->requireRunner->relativeRunnerPath = $relativeRunnerPath; $testClassTemplate->requireRunner->build(); } $fullyQualifiedTestedClassName = call_user_func_array($this->fullyQualifiedTestedClassNameExtractor, array($this, $fullyQualifiedTestClassName)); if ($this->adapter->class_exists($fullyQualifiedTestedClassName) === false) { $testClassTemplate->testMethods->testMethod->methodName = '__construct'; $testClassTemplate->testMethods->testMethod->methodName->build(); $testClassTemplate->testMethods->testMethod->build(); $testedClassPath = $this->pathFactory->build(call_user_func_array($this->testedClassPathExtractor, array($this, $fullyQualifiedTestedClassName))); $testedClassTemplate = $this->templateParser->parseFile($this->templatesDirectory . DIRECTORY_SEPARATOR . 'testedClass.php'); $testedClassTemplate->testedClassName = self::getShortClassName($fullyQualifiedTestedClassName); $testedClassTemplate->testedClassNamespace = self::getClassNamespace($fullyQualifiedTestedClassName); $testedClassPath->putContents($testedClassTemplate->build()); } else { $testedClass = new \reflectionClass($fullyQualifiedTestedClassName); foreach ($testedClass->getMethods(\reflectionMethod::IS_PUBLIC) as $publicMethod) { $testClassTemplate->testMethods->testMethod->methodName = $publicMethod->getName(); $testClassTemplate->testMethods->testMethod->methodName->build(); $testClassTemplate->testMethods->testMethod->build(); } } $testClassTemplate->testMethods->build(); $realTestClassPath->putContents($testClassTemplate->build()); return $this; }
<?php $rc = new reflectionClass('domDocument'); var_dump($rc->getExtensionName());
<?php class X { } $rc = new reflectionClass('X'); //Test invalid arguments $rc->getConstants('X'); $rc->getConstants(true); $rc->getConstants(null); $rc->getConstants('A', 'B');
protected function isExcluded(\reflectionClass $class) { $className = $class->getName(); if ($this->isInExcludedClasses($className) === true || $this->isInExcludedNamespaces($className) === true) { return true; } else { $fileName = $class->getFileName(); return $fileName === false || $this->isInExcludedDirectories($fileName) === true; } }
<?php class myClass { public $varX; public $varY; } $rc = new reflectionClass('myClass'); var_dump($rc->getExtension());
protected static function generateInterfaceCode(\reflectionClass $class, $mockNamespace, $mockClass) { return 'namespace ' . ltrim($mockNamespace, '\\') . ' {' . PHP_EOL . 'final class ' . $mockClass . ' implements \\' . $class->getName() . ', \\' . __NAMESPACE__ . '\\aggregator' . PHP_EOL . '{' . PHP_EOL . self::generateMockControllerMethod() . self::generateInterfaceMethodCode($class) . '}' . PHP_EOL . '}'; }
public function getTestedClassPath() { if ($this->testedClassPath === null) { $testedClass = new \reflectionClass($this->getTestedClassName()); $this->testedClassPath = $testedClass->getFilename(); } return $this->testedClassPath; }
public function testGetTestedClassPath() { $this->if($testedClass = new \reflectionClass($this->getTestedClassName()))->then->string($this->getTestedClassPath())->isEqualTo($testedClass->getFilename()); }
while (($file = readdir($dh)) !== false) { if (!is_dir($dir . $file)) { if (!class_exists(substr($file, 0, -4))) { require_once $dir . $file; } } } closedir($dh); } } //VERIFICAMOS TOKEN DE SEGURIDAD $db = new db_core(); if ($_POST['lib'] != "user" && $_POST['lib'] != "simulacion" && !$db->isExists('session_log', 'token', $_SESSION['token_user'])) { die('ERROR HANDLER - ERROR DE SEGURIDAD: COD 02'); } else { // LEEMOS LA LIBRERIA QUE SE REQUIERE if (isset($_POST['lib']) && $_POST['method'] && class_exists($_POST['lib'])) { $clase = $_POST['lib']; $objeto = new $clase(); $methodo = $_POST['method']; $clases = new reflectionClass($clase); if ($clases->hasMethod($methodo)) { $data = $_SERVER['HTTP_HOST'] == "localhost" || $_SERVER['HTTP_HOST'] == "127.0.0.1" ? json_decode(stripslashes($_POST['data'])) : json_decode($_POST['data']); $objeto->{$methodo}($data); } else { die("ERROR HANDLER - LLAMADA INVALIDA: COD 03"); } } else { die("ERROR HANDLER - LLAMADA INVALIDA: COD 01"); } }