/** * Add all the routes in the router in parameter * @param $router Router */ public function generateRoute(Router $router) { foreach ($this->classes as $class) { $classMethods = get_class_methods($this->namespace . $class . 'Controller'); $rc = new \ReflectionClass($this->namespace . $class . 'Controller'); $parent = $rc->getParentClass(); $parent = get_class_methods($parent->name); $className = $this->namespace . $class . 'Controller'; foreach ($classMethods as $methodName) { if (in_array($methodName, $parent) || $methodName == 'index') { continue; } else { foreach (Router::getSupportedHttpMethods() as $httpMethod) { if (strstr($methodName, $httpMethod)) { continue 2; } if (in_array($methodName . $httpMethod, $classMethods)) { $router->add('/' . strtolower($class) . '/' . $methodName, new $className(), $methodName . $httpMethod, $httpMethod); unset($classMethods[$methodName . $httpMethod]); } } $router->add('/' . strtolower($class) . '/' . $methodName, new $className(), $methodName); } } $router->add('/' . strtolower($class), new $className(), 'index'); } }
function writeMethods(ReflectionClass $class, $fp) { if ($class->getParentClass()) { writeMethods($class->getParentClass(), $fp); } foreach ($class->getMethods() as $method) { if (!$method->isPublic() || $method->getName() === '__construct' || substr($method->getName(), 0, 3) === 'set' || substr($method->getName(), 0, 3) === 'add') { continue; } $return = ''; $description = ''; foreach (explode("\n", $method->getDocComment()) as $line) { $line = ltrim(trim(trim(trim($line), '*')), '/'); if (strpos($line, '@return') === 0) { $return = trim(substr($line, 7)); $return = preg_replace_callback('~[A-Z][a-zA-Z]+~', function ($match) { if ($match[0] === '\\DateTime' || $match[0] === 'DateTime') { return $match[0]; } return '[' . $match[0] . '](#' . strtolower($match[0]) . ')'; }, $return); $return = str_replace('|', '|', $return); } elseif (strpos($line, '@') !== 0 && !empty($line)) { $description = $line; } } $parameters = []; foreach ($method->getParameters() as $parameter) { $parameters[] = $parameter->getName(); } fwrite($fp, '| ' . $method->getName() . " | {$return} | " . implode(', ', $parameters) . " | {$description} |\n"); } }
/** * @return bool|\PHPStan\Reflection\ClassReflection */ public function getParentClass() { if ($this->reflection->getParentClass() === false) { return false; } return $this->broker->getClass($this->reflection->getParentClass()->getName()); }
/** * Get a hierarchy of contexts for the given class as an array * * @param string $class * @return array */ private function getContexts($class) { if ($class == Wires_Locator_Interface::GLOBAL_CONTEXT) { return array($class); } $ref = new ReflectionClass($class); $contexts = array($class); // collect interfaces if (is_array($ref->getInterfaceNames())) { foreach ($ref->getInterfaceNames() as $interface) { $contexts[] = $interface; } } // add parent class if ($ref->getParentClass()) { $parent_contexts = $this->getContexts($ref->getParentClass()->getName()); foreach ($parent_contexts as $pc) { if ($pc != Wires_Locator_Interface::GLOBAL_CONTEXT && !in_array($pc, $contexts)) { $contexts[] = $pc; } } } $contexts[] = Wires_Locator_Interface::GLOBAL_CONTEXT; return $contexts; }
public function create_controller($request) { $loaded = false; foreach ($this->context->load_paths() as $path) { if (list($controller_file, $controller_class) = $this->load_controller($request->parameter('controller'), $path)) { $loaded = true; break; } } if ($loaded === false) { throw new Exception('Cannot load controller `' . $request->parameter('controller') . '`, searched in `' . join(', ', $this->context->load_paths()) . '`'); } // load ApplicationController if any. foreach ($this->context->load_paths() as $load_path) { if (file_exists($load_path . 'app/controllers/application.php')) { require $load_path . 'app/controllers/application.php'; if (class_exists('ApplicationController')) { break; } } } require $controller_file; if (false === class_exists($controller_class)) { throw new Exception('Expected `' . $controller_file . '` to define `' . $controller_class . '`'); } $rclass = new ReflectionClass($controller_class); if (false === ($rclass->getParentClass() || $rclass->getParentClass() == 'ApplicationController' || $rclass->getParentClass() == 'ActionController')) { throw new Exception('Expected `' . $controller_class . '` to extend ApplicationController(recommended) or ActionControler'); } // XXX: the $path $this->context->logger()->debug(str_replace($path, '${' . $this->context->config()->application_name() . '}/', $controller_file) . ' --> ' . $controller_class); return $rclass->newInstance($this->context); }
/** * Loads from annotations from a directory. * * @param string $path A directory path * @param string $type The resource type * * @return EventsMap A event map * * @throws \InvalidArgumentException When annotations can't be parsed */ public function load($path, $type = null) { $dir = $this->locator->locate($path); $map = new EventsMap(); $map->addResource(new DirectoryResource($dir, '/Event\\.php$/')); $files = iterator_to_array(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir), \RecursiveIteratorIterator::LEAVES_ONLY)); usort($files, function (\SplFileInfo $a, \SplFileInfo $b) { return (string) $a > (string) $b ? 1 : -1; }); foreach ($files as $file) { if (!$file->isFile() || 'Event.php' !== substr($file->getFilename(), -9)) { continue; } if ($class = $this->findClass($file)) { $refl = new \ReflectionClass($class); if ($refl->isAbstract()) { continue; } if (!$refl->getParentClass() || $refl->getParentClass()->getName() != 'Symfony\\Component\\EventDispatcher\\Event') { continue; } $map->merge($this->loader->load($class, $type)); } } return $map; }
/** * @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; }
/** * * Recursive properties extraction. Returns properties of the $reflectedClass and parents. * * @param \ReflectionClass $reflectedClass * @param int $filter * @return \ReflectionProperty[] */ private function extractProperties(\ReflectionClass $reflectedClass, $filter) { $result = $reflectedClass->getProperties($filter); if ($reflectedClass->getParentClass()) { $result = array_merge($result, $this->extractProperties($reflectedClass->getParentClass(), $filter)); } return $result; }
private function getTraitNames(\ReflectionClass $class) : array { $traitNames = $class->getTraitNames(); while ($class->getParentClass() !== false) { $traitNames = array_values(array_unique(array_merge($traitNames, $class->getParentClass()->getTraitNames()))); $class = $class->getParentClass(); } return $traitNames; }
protected function injectTestCaseHierarchy(AbstractTestCase $testCase) { $rc = new \ReflectionClass($testCase); while ($rc->getParentClass()) { $class = $rc->getParentClass()->getName(); $testCase->getDi()->instanceManager()->addSharedInstance($testCase, $class); $rc = new \ReflectionClass($class); } }
/** * @param \ReflectionClass $class * @return \ReflectionClass[] */ public function getClassParents(\ReflectionClass $class) { if ($class->getParentClass()) { $parents = $this->getClassParents($class->getParentClass()); $p = array($class->getParentClass()); return array_merge($p, $parents); } else { return array(); } }
protected function traitsUsedRecursive($class, $traitNames = []) { if (!$class instanceof ReflectionClass) { $class = new ReflectionClass($class); } $traitNames = array_merge($traitNames, $class->getTraitNames()); if ($class->getParentClass() != false) { return array_merge($traitNames, $this->traitsUsedRecursive($class->getParentClass())); } return $traitNames; }
/** * Method that extract all the properties of a class * @param string $class * @return array */ public static function getClassProperties($class) { $properties = []; Logger::log('Extracting annotations properties from class ' . $class); $selfReflector = new \ReflectionClass($class); if (false !== $selfReflector->getParentClass()) { $properties = self::getClassProperties($selfReflector->getParentClass()->getName()); } $properties = array_merge($properties, self::extractProperties($selfReflector)); return $properties; }
protected function addDependency(array &$loadPaths, \ReflectionClass $dep) { if ($dep->getFileName() !== false) { $loadPaths[$dep->getName()] = $dep->getFileName(); } if ($dep->getParentClass() instanceof \ReflectionClass) { $this->addDependency($loadPaths, $dep->getParentClass()); } foreach ($dep->getInterfaces() as $interface) { $this->addDependency($loadPaths, $interface); } }
/** * @param \ReflectionClass $class * * @return array */ private function _getClassProperties(\ReflectionClass $class) { $props = []; if ($class->getParentClass()) { $props = $this->_getClassProperties($class->getParentClass()); } foreach ($class->getProperties() as $property) { if (!in_array($property->getName(), $props)) { $props[] = $property->getName(); } } return $props; }
/** * compile class recursively * @param string $pClass */ private function compileClass($pClass) { $rf = new \ReflectionClass($pClass); if (!$rf->getParentClass()) { $intArr = $rf->getInterfaceNames(); if (count($intArr) > 0) { foreach ($intArr as $interface) { \bcompiler_write_class($this->fileHandle, $interface); } } } else { $this->compileClass($rf->getParentClass()); } }
function __construct() { $front = Zend_Controller_Front::getInstance(); $event_handlers = array(); $filters = array(); $dir = new DirectoryIterator(APPLICATION_DIRECTORY . "/plugins"); $plugins = array(); foreach ($dir as $file) { $className = $file->getFilename(); if ($file->isDir() && $className[0] != '.' && $className[0] != '_') { if (file_exists("plugins/{$className}/{$className}.php") && file_exists("plugins/{$className}/config.xml")) { Zend_Loader::loadFile("plugins/{$className}/{$className}.php"); $class = new ReflectionClass($className); if ($class->getParentClass() && ($class->getParentClass()->getName() == "Joobsbox_Plugin_Base" || $class->getParentClass()->getName() == "Joobsbox_Plugin_AdminBase")) { foreach ($class->getMethods() as $method) { $methodName = $method->getName(); if (strpos($methodName, "event_") !== FALSE) { $eventName = substr($methodName, strpos($methodName, "_") + 1); $event_handlers[$eventName][] = $className; } elseif (strpos($methodName, "filter_") !== FALSE) { $filterName = substr($methodName, strpos($methodName, "_") + 1); $filters[$filterName][] = $className; } } $plugins[$className] = new $className(); if ($class->getParentClass()->getName() == "Joobsbox_Plugin_AdminBase") { $plugins[$className]->isAdmin = true; } $plugins[$className]->conf = new Zend_Config_Xml("plugins/{$className}/config.xml"); $plugins[$className]->path = "plugins/{$className}"; if (method_exists($plugins[$className], 'setPluginName')) { $plugins[$className]->setPluginName($className); } if (method_exists($plugins[$className], 'initPlugin')) { $plugins[$className]->initPlugin(); } if (method_exists($plugins[$className], 'init')) { $plugins[$className]->init(); } if (method_exists($plugins[$className], 'startup')) { $plugins[$className]->startup(); } } } } } Zend_Registry::set("event_handler_plugins", $event_handlers); Zend_Registry::set("filter_plugins", $filters); Zend_Registry::set("plugins", $plugins); }
public function run() { $pattern = array('app', 'code', 'local', '*', '*', 'Test', 'Mink'); $pattern = Mage::getBaseDir() . DS . implode(DS, $pattern); $files = $this->_getTestClasses($pattern); $renderer = $this->_getOutputRenderer(); if (empty($files)) { $renderer->output($renderer->bold('No test class found')); } else { try { require_once 'mink.phar'; Mage::getSingleton('core/session', array('name' => 'frontend'))->start(); $renderer->section('SCRIPT START'); $renderer->output(sprintf('Found %d file%s', count($files), count($files) > 1 ? 's' : '')); foreach ($files as $file) { $start = strrpos($file, 'local'); $classPath = substr($file, $start + 6); $className = basename(implode('_', explode(DS, $classPath)), '.php'); if (!class_exists($className)) { $renderer->error(sprintf('Class %s does not exist', $className)); continue; } $object = new $className($renderer); $reflection = new ReflectionClass($className); if (!$reflection->getParentClass() || $reflection->getParentClass()->getName() !== 'JR_Mink_Test_Mink') { $renderer->error(sprintf('Class %s must extend JR_Mink_Test_Mink class', $className)); continue; } $methods = $reflection->getMethods(ReflectionMethod::IS_PUBLIC); foreach ($methods as $method) { if (substr($method->getName(), 0, 4) !== 'test') { continue; } try { $object->{$method->getName()}(); } catch (Exception $e) { Mage::logException($e); $renderer->error($e->getMessage()); } } } $renderer->section('SCRIPT END'); } catch (Exception $e) { Mage::logException($e); $renderer->error($e->getMessage(), false, true); } } }
/** * Injects the data in the class * @param object $object The object to inject the data in * @return object The instanciated class with its loaded properties */ public function injectData($object = null) { if ($object !== null) { $reflection = new \ReflectionClass($object); if ($reflection->getParentClass()->name !== $this->reflection->name) { throw new \LogicException('You can only inject data in a class of the same type'); } $class = $object; } else { $reflection = $this->reflection; $class = $this->reflection->newInstanceWithoutConstructor(); } foreach ($this->data as $key => $value) { $prop = $reflection->getProperty($key); $prop->setAccessible(true); // When the value given only is a reference, load it. if ($value instanceof Reference) { $value = $value->loadRef(); } elseif (is_array($value)) { $value = self::injectDataInArray($value); } $prop->setValue($class, $value); } return $class; }
/** * Lists all User models. * @return mixed */ public function actionIndex() { $searchModel = \Yii::createObject(UserSearch::className()); $dataProvider = $searchModel->search($_GET); // Remove any default orderings // $dataProvider->query->orderBy = null; $sort = new Sort(['attributes' => $searchModel->filterableAttributes()]); if (!empty($sort->orders)) { $dataProvider->query->orderBy = null; } else { if (BehaviorHelper::hasBehavior($searchModel, \mata\arhistory\behaviors\HistoryBehavior::class)) { $dataProvider->query->select('*'); $reflection = new \ReflectionClass($searchModel); $parentClass = $reflection->getParentClass(); $alias = $searchModel->getTableSchema()->name; $pk = $searchModel->getTableSchema()->primaryKey; if (is_array($pk)) { if (count($pk) > 1) { throw new NotFoundHttpException('Combined primary keys are not supported.'); } $pk = $pk[0]; } $aliasWithPk = $alias . '.' . $pk; $dataProvider->query->join('INNER JOIN', 'arhistory_revision', 'arhistory_revision.DocumentId = CONCAT(:class, ' . $aliasWithPk . ')', [':class' => $parentClass->name . '-']); $dataProvider->query->andWhere('arhistory_revision.Revision = (SELECT MAX(Revision) FROM `arhistory_revision` WHERE arhistory_revision.`DocumentId` = CONCAT(:class, ' . $aliasWithPk . '))', [':class' => $parentClass->name . '-']); $dataProvider->query->orderBy('arhistory_revision.DateCreated DESC'); } } $dataProvider->setSort($sort); return $this->render("index", ['searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'sort' => $sort]); }
public function getModuleActions($module_class, $use_admin_prefix = false) { $actions = array(); $controllers_dir = MODULES_PATH . lcfirst(str_replace('Module', '', $module_class)) . '/controllers/'; $controllers = scandir($controllers_dir); foreach ($controllers as $controller) { if ($controller[0] == ".") { continue; } $class = str_replace('.php', '', $controller); if (!class_exists($class, false)) { require_once $controllers_dir . $controller; } $reflection = new ReflectionClass($class); if (!in_array($reflection->getParentClass()->name, array('BaseController', 'AdminController'))) { continue; } $actions_titles = call_user_func(array($class, 'actionsTitles')); $methods = $reflection->getMethods(ReflectionMethod::IS_PUBLIC); foreach ($methods as $method) { if (in_array($method->name, array('actionsTitles', 'actions')) || mb_substr($method->name, 0, 6, 'utf-8') != 'action') { continue; } $action = str_replace('action', '', $method->name); $action_name = str_replace('Controller', '', $class) . '_' . $action; $title = isset($actions_titles[$action]) ? $actions_titles[$action] : ""; if ($title && $use_admin_prefix && strpos($action_name, "Admin_") !== false) { $title .= " (админка)"; } $actions[$action_name] = $title; } } return $actions; }
protected function getPropertiesFromAnnotations(\ReflectionClass $reflection, $scalar_only = false, $return_data_types = false) { $properties = array(); $docblock_entries = explode("\n", $reflection->getDocComment()); foreach ($docblock_entries as $entry) { $property_start = strpos($entry, '@property'); if ($property_start !== false) { $property_elements = explode(' ', substr($entry, $property_start + 10)); if (count($property_elements) == 2) { if (!$scalar_only) { $properties[str_replace('$', '', trim($property_elements[1]))] = $property_elements[0]; } else { switch ($property_elements[0]) { case 'int': case 'integer': case 'bool': case 'boolean': case 'string': case 'double': case 'float': case 'decimal': case 'array': $properties[str_replace('$', '', trim($property_elements[1]))] = $property_elements[0]; break; } } } } } $parent = $reflection->getParentClass(); if ($parent) { $properties = array_merge($properties, $this->getPropertiesFromAnnotations($parent, $scalar_only, true)); } return $return_data_types ? $properties : array_keys($properties); }
/** * Casts objects to arrays and adds the dynamic property prefix. * * @param object $obj The object to cast * @param \ReflectionClass $reflector The class reflector to use for inspecting the object definition * * @return array The array-cast of the object, with prefixed dynamic properties */ public static function castObject($obj, \ReflectionClass $reflector) { if ($reflector->hasMethod('__debugInfo')) { $a = $obj->__debugInfo(); } elseif ($obj instanceof \Closure) { $a = array(); } else { $a = (array) $obj; } if ($obj instanceof \__PHP_Incomplete_Class) { return $a; } if ($a) { $combine = false; $p = array_keys($a); foreach ($p as $i => $k) { if (isset($k[0]) && "" !== $k[0] && !$reflector->hasProperty($k)) { $combine = true; $p[$i] = self::PREFIX_DYNAMIC . $k; } elseif (isset($k[16]) && "" === $k[16] && 0 === strpos($k, "class@anonymous")) { $combine = true; $p[$i] = "" . $reflector->getParentClass() . '@anonymous' . strrchr($k, ""); } } if ($combine) { $a = array_combine($p, $a); } } return $a; }
/** * Searches a given annotation for a specified property. If given, the value is returned, otherwise (when not found) null is returned. * * @param string $strProperty * @param string $strAnnotation * @param class_reflection_enum $objEnum - whether to return annotation values or parameters, default is values * * @return null|string */ public function getAnnotationValueForProperty($strProperty, $strAnnotation, class_reflection_enum $objEnum = null) { if ($objEnum == null) { $objEnum = class_reflection_enum::VALUES(); } $arrProperties = $this->objReflectionClass->getProperties(); foreach ($arrProperties as $objOneProperty) { if ($objOneProperty->getName() == $strProperty) { $strFirstAnnotation = $this->searchFirstAnnotationInDoc($objOneProperty->getDocComment(), $strAnnotation); if ($objEnum->equals(class_reflection_enum::VALUES())) { $strFirstAnnotation = $strFirstAnnotation["values"][0]; } else { if ($objEnum->equals(class_reflection_enum::PARAMS())) { $strFirstAnnotation = $strFirstAnnotation["params"][0]; } } if ($strFirstAnnotation !== false) { return $strFirstAnnotation; } } } //check if there's a base-class -> inheritance $objBaseClass = $this->objReflectionClass->getParentClass(); if ($objBaseClass !== false) { $objBaseAnnotations = new class_reflection($objBaseClass->getName()); return $objBaseAnnotations->getAnnotationValueForProperty($strProperty, $strAnnotation, $objEnum); } return null; }
public function getParentClass() { $phpReflection = parent::getParentClass(); $zendReflection = new Zend_Reflection_Class($phpReflection->getName()); unset($phpReflection); return $zendReflection; }
function getMethodAnnotations($className) { static $methods = []; if (isset($methods[$className])) { return $methods[$className]; } $class = new ReflectionClass($className); foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $k => $method) { $methodName = $method->getName(); // It's easier to hardcode asConfig() than properly dig through ancestry if ($methodName === 'asConfig') { $methods[$className]['asConfig'] = 'array asConfig()'; continue; } $doc = $method->getDocComment(); if (strpos($doc, '{@inheritdoc}') !== false) { $parentMethods = getMethodAnnotations($class->getParentClass()->getName()); $methods[$className][$methodName] = $parentMethods[$methodName]; continue; } $returnType = preg_match('(@return\\s*(\\S+))', $doc, $m) ? $m[1] : 'void'; preg_match_all('(@param\\s+(\\S+)\\s+(\\S+))', $doc, $matches, PREG_SET_ORDER); $args = []; foreach ($matches as $m) { $args[] = $m[1] . ' ' . $m[2]; } $methods[$className][$methodName] = str_pad($returnType, 7) . ' ' . $methodName . '(' . implode(', ', $args) . ')'; } ksort($methods[$className]); return $methods[$className]; }
public function loadMetadataForClass(\ReflectionClass $class) { $metadata = new ClassMetadata($className = $class->getName()); if (false !== ($filename = $class->getFilename())) { $metadata->fileResources[] = $filename; } // this is a bit of a hack, but avoids any timeout issues when a class // is moved into one of the compiled classes files, and Doctrine // Common 2.1 is used. if (false !== strpos($filename, '/classes.php') || false !== strpos($filename, '/bootstrap.php')) { return null; } $hasInjection = false; if ($parentClass = $class->getParentClass()) { $this->buildAnnotations($parentClass, $metadata); $this->buildProperties($parentClass, $metadata, $hasInjection); // temp disabledavoid test failing, only child lookup for now // @todo fix test failing Cannot redeclare class EnhancedProxy_...SecuredController in EnhancedProxy___CG__-JMS-DiExtraBundle-Tests-Functional-Bundle-TestBundle-Controller-SecuredController.php on line 11 //$this->buildMethods($parentClass, $metadata, $hasInjection); } $this->buildAnnotations($class, $metadata); $this->buildProperties($class, $metadata, $hasInjection); $this->buildMethods($class, $metadata, $hasInjection); if (null == $metadata->id && !$hasInjection) { return null; } return $metadata; }
/** * @see \Cosma\Bundle\TestingBundle\TestCase\ElasticTestCase::setUp */ public function testSetUp() { $testCase = $this->getMockBuilder('Cosma\\Bundle\\TestingBundle\\TestCase\\ElasticTestCase')->disableOriginalConstructor()->setMethods(['recreateIndex'])->getMockForAbstractClass(); $testCase->expects($this->once())->method('recreateIndex'); $reflectionClass = new \ReflectionClass($testCase); $classProperty = $reflectionClass->getParentClass()->getProperty('class'); $classProperty->setAccessible(true); $classProperty->setValue($testCase, 'Cosma\\Bundle\\TestingBundle\\Tests\\AppKernel'); $method = $reflectionClass->getParentClass()->getMethod('setUp'); $method->setAccessible(true); $method->invoke($testCase); $kernelProperty = $reflectionClass->getProperty('kernel'); $kernelProperty->setAccessible(true); $kernel = $kernelProperty->getValue(); $this->assertInstanceOf('Cosma\\Bundle\\TestingBundle\\Tests\\AppKernel', $kernel, 'set up is wrong'); }
/** * @param RESTApiRequest $request * @return RESTApiResource * @throws \Exception * @throws RESTNotFound */ public function getTarget(RESTApiRequest $request) { $resources_chain = $request->getResource(); $target = null; for ($i = 0; $i < count($resources_chain); $i++) { try { $class_name = $this->getClassForResource($resources_chain[$i]); } catch (\Exception $e) { continue; } $reflection = new \ReflectionClass($class_name); $parent = $reflection->getParentClass(); $parent_name = explode('\\', $parent->getName()); $parent_name = $parent_name[count($parent_name) - 1]; if (in_array($parent_name, array("RESTApiCollection", "RESTApiStore", "RESTApiController"))) { $this->nested_params[$resources_chain[$i]] = isset($resources_chain[$i + 1]) ? $resources_chain[$i + 1] : ""; } else { if ($parent_name == "RESTApiDocument") { continue; } else { throw new \Exception("Undefined resource type"); } } if ($parent_name == "RESTApiCollection") { $target = $resources_chain[$i]; } } if (empty($target)) { throw new RESTNotFound("Resource not found"); } $idx = array_search($target, $resources_chain); $external_params = array_slice($resources_chain, $idx + 1); array_pop($this->nested_params); return new $class_name($this->nested_params, $external_params); }
public function __construct() { /** * 实例化容器,并且保存在此载体中 */ if (empty(static::$app)) { static::$app = new Application(); } /** * 通过反射获取所有父类,并且获取他们的类名,通过这些类名来形成构造函数 * 比如当前类的构造函数为 $this->OBlood() * 切记:Application类不能继承此类 */ $reflectionClass = new \ReflectionClass($this); $constructs[] = $reflectionClass->getShortName(); $parentClass = $reflectionClass->getParentClass(); while ($parentClass != false) { $constructs[] = $parentClass->getShortName(); $parentClass = $parentClass->getParentClass(); } /** * 这里采用倒叙的方式来进行排列, * 主要是以顶级父类为最先执行,一次向下 */ rsort($constructs); foreach ($constructs as $construct) { if (method_exists($this, $construct)) { call_user_func_array([$this, $construct], func_get_args()); } } }