public function __construct(DiInterface $di, $class) { if (!is_string($class) && !is_object($class)) { throw new Exception("第二个参数只能接受字符串或对象"); } $this->_di = $di; $this->_class = new ReflectionClass($class); if (is_object($class)) { $this->_instance = $class; } elseif (is_string($class) && !$this->_class->isInstantiable()) { throw new Exception("不能对一个无法实例化的类进行注入"); } $this->_interfaceNames = $this->_class->getInterfaceNames(); }
public static function run() { // run setup and prepare env static::setup(); // handle the requested uri $uri = static::parse(); $segments = array(); if (strlen($uri)) { $segments = explode('/', $uri); } // lets log our translated uri Log::info('Translated URI: ' . $uri); // set our action or our default if none is set $action = count($segments) ? array_shift($segments) : 'page'; // default to our front end router $controller = 'Routes'; // set the template path $theme = Config::get('metadata.theme'); Template::path(PATH . 'themes/' . $theme . '/'); // remove admin as an argument and set the default action if there isnt one if ($action == 'admin') { // set default controller for the admin $controller = (count($segments) ? array_shift($segments) : 'posts') . '_controller'; // set default action $action = count($segments) ? array_shift($segments) : 'index'; // public admin actions $public = array('users/login', 'users/amnesia', 'users/reset'); // redirect to login if (Users::authed() === false and in_array(trim($controller, '_controller') . '/' . $action, $public) === false) { return Response::redirect(Config::get('application.admin_folder') . '/users/login'); } // set template path for admin Template::path(PATH . 'system/admin/theme/'); } // log the controller we are going to use and the action Log::info('Controller action: ' . $controller . '/' . $action); // check we can find a action $reflector = new ReflectionClass($controller); if ($reflector->isInstantiable() === false or $reflector->hasMethod($action) === false) { // default back to front end template for 404 page Template::path(PATH . 'themes/' . $theme . '/'); // report error Log::warning($reflector->isInstantiable() === false ? 'Controller was not Instantiable' : 'Action does not exist'); // method not found in controller return Response::error(404); } $reflector->getMethod($action)->invokeArgs(new $controller(), $segments); }
public function doaction($name) { if (isset(self::$action_info[$name])) { try { global $plugin; //var_dump(self::$action_info); if (file_exists(dirname(__FILE__) . "/{$plugin}/" . self::$action_info[$name]['file'])) { include_once dirname(__FILE__) . "/{$plugin}/" . self::$action_info[$name]['file']; } if (isset(self::$action_info[$name]['class'])) { $classname = self::$action_info[$name]['class']; $class = new ReflectionClass($classname); if ($class->isInstantiable()) { $methodname = self::$action_info[$name]['method']; $method = $class->newInstance(); $path = $method->{$methodname}(); //global $plugin; header("Location: " . $plugin . "/" . self::$action_info[$name]['returns'][$path]); //require(dirname(__file__)."../../".self::$action_info[$name]['returns'][$path]); } } else { $method = self::$action_info[$name]['method']; $path = $method(); global $plugin; header("Location: " . $plugin . "/" . self::$action_info[$name]['returns'][$path]); } } catch (Exception $e) { echo "在反射解释{$name} 出现错误\n"; } } else { header("Location: help/noaction.html"); } }
/** * Get Global Application CMS accessibility scope. * * @access public * @static * @uses Core\Config() * * @return array */ public static function getAccessibilityScope() { $scope = glob(Core\Config()->paths('mode') . 'controllers' . DIRECTORY_SEPARATOR . '*.php'); $builtin_scope = array('CMS\\Controllers\\CMS'); $builtin_actions = array(); $accessibility_scope = array(); foreach ($builtin_scope as $resource) { $builtin_actions = array_merge($builtin_actions, get_class_methods($resource)); } $builtin_actions = array_filter($builtin_actions, function ($action) { return !in_array($action, array('create', 'show', 'edit', 'delete', 'export'), true); }); foreach ($scope as $resource) { $resource = basename(str_replace('.php', '', $resource)); if ($resource !== 'cms') { $controller_name = '\\CMS\\Controllers\\' . $resource; $controller_class = new \ReflectionClass($controller_name); if (!$controller_class->isInstantiable()) { continue; } /* Create instance only if the controller class is instantiable */ $controller_object = new $controller_name(); if ($controller_object instanceof CMS\Controllers\CMS) { $accessibility_scope[$resource] = array_diff(get_class_methods($controller_name), $builtin_actions); array_push($accessibility_scope[$resource], 'index'); foreach ($accessibility_scope[$resource] as $key => $action_with_acl) { if (in_array($action_with_acl, $controller_object->skipAclFor, true)) { unset($accessibility_scope[$resource][$key]); } } } } } return $accessibility_scope; }
public function run() { foreach (Finder::findFiles('*Test.php')->from(__DIR__) as $fileInfo) { /** @var \SplFileInfo $fileInfo*/ $baseName = $fileInfo->getBasename('.php'); if ($baseName === 'PhpRQTest') { continue; } $className = 'PhpRQ\\' . $baseName; $reflection = new \ReflectionClass($className); if (!$reflection->isInstantiable()) { continue; } foreach ($reflection->getMethods() as $method) { if (!$method->isPublic() || strpos($methodName = $method->getName(), 'test') === false) { continue; } $phpdoc = $method->getDocComment(); if ($phpdoc !== false && ($providerPos = strpos($phpdoc, '@dataProvider')) !== false) { $providerMethodPos = $providerPos + 14; $providerMethodLen = strpos($phpdoc, "\n", $providerMethodPos) - $providerMethodPos; $providerMethod = substr($phpdoc, $providerMethodPos, $providerMethodLen); $testCase = new $className($this->provider->getRedisClient()); foreach ($testCase->{$providerMethod}() as $args) { $testCase = new $className($this->provider->getRedisClient()); call_user_func_array([$testCase, $methodName], (array) $args); } } else { $testCase = new $className($this->provider->getRedisClient()); $testCase->{$methodName}(); } } } }
function find_classes($input, $recursive = true) { $classes = array(); if (is_file($input)) { if (preg_match('/\\.php$/', $input)) { $classes = determine_classes($input); } } elseif (is_dir($input)) { $iter = null; if ($recursive) { $iter = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($input), RecursiveIteratorIterator::LEAVES_ONLY); } else { $iter = new DirectoryIterator($input); } foreach ($iter as $i) { if ($i->isFile()) { if (preg_match('/\\.php$/', $i)) { $found = determine_classes($i->getPathname()); $classes = array_merge($classes, $found); } } } } $classes = array_unique($classes); $found = array(); foreach ($classes as $c) { $rc = new \ReflectionClass($c); if ($rc->isInstantiable()) { $found[] = $c; } } return $found; }
/** * 自动绑定(Autowiring)自动解析(Automatic Resolution) * * @param string $className * @return object * @throws Exception */ public function build($className) { var_dump($className); // 如果是匿名函数(Anonymous functions),也叫闭包函数(closures) if ($className instanceof \Closure) { // 执行闭包函数,并将结果 return $className($this); } /** @var ReflectionClass $reflector */ $reflector = new \ReflectionClass($className); // 检查类是否可实例化, 排除抽象类abstract和对象接口interface if (!$reflector->isInstantiable()) { throw new Exception("Can't instantiate this."); } /** @var ReflectionMethod $constructor 获取类的构造函数 */ $constructor = $reflector->getConstructor(); // 若无构造函数,直接实例化并返回 if (is_null($constructor)) { return new $className(); } // 取构造函数参数,通过 ReflectionParameter 数组返回参数列表 $parameters = $constructor->getParameters(); // 递归解析构造函数的参数 $dependencies = $this->getDependencies($parameters); // 创建一个类的新实例,给出的参数将传递到类的构造函数。 return $reflector->newInstanceArgs($dependencies); }
/** * @param $name * @return mixed * @throws \Exception */ public function getInstance($name) { if (!is_string($name)) { throw new \Exception('Name must be a string'); } $name = rtrim($name, '\\'); if (isset($this->instance[$name])) { return $this->instance[$name](); } else { $reflectionClass = new \ReflectionClass($name); if (!$reflectionClass->isInstantiable()) { throw new \Exception('Class ' . $name . ' is not instantiable'); } $constructor = $reflectionClass->getConstructor(); if (!is_null($constructor)) { $parameters = $constructor->getParameters(); $params = $this->getReflectionParametersValues($parameters); } else { $params = array(); } $this->setInstance($name, function () use($reflectionClass, $params) { return $reflectionClass->newInstanceArgs($params); }); return $this->getInstance($name); } }
/** * Returns the definition as string representation. * * @return string */ public function dump(ObjectDefinition $definition) { $className = $definition->getClassName(); $classExist = class_exists($className) || interface_exists($className); // Class if (!$classExist) { $warning = '#UNKNOWN# '; } else { $class = new \ReflectionClass($className); $warning = $class->isInstantiable() ? '' : '#NOT INSTANTIABLE# '; } $str = sprintf(' class = %s%s', $warning, $className); // Scope $str .= PHP_EOL . ' scope = ' . $definition->getScope(); // Lazy $str .= PHP_EOL . ' lazy = ' . var_export($definition->isLazy(), true); if ($classExist) { // Constructor $str .= $this->dumpConstructor($className, $definition); // Properties $str .= $this->dumpProperties($definition); // Methods $str .= $this->dumpMethods($className, $definition); } return sprintf('Object (' . PHP_EOL . '%s' . PHP_EOL . ')', $str); }
function find_handler($path) { global $g_maps; $route_path = substr($path, 5); if ($g_maps && isset($g_maps[$route_path])) { $object = $g_maps[$route_path]['class']; $action = $g_maps[$route_path]['method']; } else { if (preg_match('/^\\/rest\\/(\\w+)\\/(\\w+)\\/?[^\\/]*$/i', $path, $ret)) { $object = $ret[1]; $action = $ret[2]; } } if (isset($object) && isset($action)) { try { $class_file = CLASSES_PATH . "/{$object}.php"; if (file_exists($class_file)) { require_once $class_file; $class = new ReflectionClass($object); if ($class->isInstantiable()) { return array('class' => $class->newInstance(), 'method' => new ReflectionMethod($object, $action)); } } } catch (Exception $e) { } } return null; }
/** * get callable methods within the classObj * * @param string|object $classObj * @param int $filter * @param bool $filterOwn * @return array array of \ReflectionMethod */ public function getCallableMethods($classObj, $filter, $filterOwn = true) { if (is_string($classObj) && !class_exists($classObj, false)) { throw new ClassNotDefinedException('Class name: ' . $classObj . ' not defined yet!'); } $className = $classObj; if (is_object($classObj)) { $className = get_class($classObj); } $reflectClass = new \ReflectionClass($classObj); $methods = array(); if (!$reflectClass->isUserDefined() || !$reflectClass->isInstantiable()) { return $methods; } $methods = $reflectClass->getMethods($filter); if ($filterOwn) { $needNeaten = false; foreach ($methods as $k => $method) { if ($method->class != $className) { unset($methods[$k]); !$needNeaten && ($needNeaten = true); } } $needNeaten && ($methods = array_values($methods)); } return $methods; }
/** * @param object $entity * * @return MetaInformation * * @throws \RuntimeException if no declaration for document found in $entity */ public function loadInformation($entity) { $className = $this->getClass($entity); if (!is_object($entity)) { $reflectionClass = new \ReflectionClass($className); if (!$reflectionClass->isInstantiable()) { throw new \RuntimeException(sprintf('cannot instantiate entity %s', $className)); } $entity = $reflectionClass->newInstanceWithoutConstructor(); } if (!$this->annotationReader->hasDocumentDeclaration($entity)) { throw new \RuntimeException(sprintf('no declaration for document found in entity %s', $className)); } $metaInformation = new MetaInformation(); $metaInformation->setEntity($entity); $metaInformation->setClassName($className); $metaInformation->setDocumentName($this->getDocumentName($className)); $metaInformation->setFieldMapping($this->annotationReader->getFieldMapping($entity)); $metaInformation->setFields($this->annotationReader->getFields($entity)); $metaInformation->setRepository($this->annotationReader->getRepository($entity)); $metaInformation->setIdentifier($this->annotationReader->getIdentifier($entity)); $metaInformation->setBoost($this->annotationReader->getEntityBoost($entity)); $metaInformation->setSynchronizationCallback($this->annotationReader->getSynchronizationCallback($entity)); $metaInformation->setIndex($this->annotationReader->getDocumentIndex($entity)); $metaInformation->setIsDoctrineEntity($this->annotationReader->isDoctrineEntity($entity)); return $metaInformation; }
/** * Load the resource map * * @return $this */ public function loadResourceMap() { $dirIterator = new \RecursiveDirectoryIterator($this->path->getDir('vendor/devvoh/parable/src'), \RecursiveDirectoryIterator::SKIP_DOTS); $iteratorIterator = new \RecursiveIteratorIterator($dirIterator); foreach ($iteratorIterator as $path => $file) { /** @var \SplFileInfo $file */ /* * Specifically exclude all non-php files and Bootstrap, since it will attempt to register everything again * and isn't a class anyway. */ if ($file->getFilename() === 'Bootstrap.php' || $file->getFilename() === 'parable.php' || $file->getExtension() !== 'php' || strpos($file->getRealPath(), '/Cli/') !== false) { continue; } $className = str_replace('.' . $file->getExtension(), '', $file->getFilename()); $fullClassName = str_replace($this->path->getDir('vendor/devvoh/parable/src'), '', $file->getRealPath()); $fullClassName = str_replace('.' . $file->getExtension(), '', $fullClassName); $fullClassName = str_replace('/', '\\', 'Parable' . $fullClassName); $reflectionClass = new \ReflectionClass($fullClassName); if (!$reflectionClass->isInstantiable()) { continue; } $this->resourceMap[$className] = $fullClassName; } return $this; }
/** * Returns an array of variants. * * With no arguments, returns all variants * * With a classname as the first argument, returns the variants that apply to that class * (optionally including subclasses) * * @static * @param string $class - The class name to get variants for * @param bool $includeSubclasses - True if variants should be included if they apply to at least one subclass of $class * @return array - An array of (string)$variantClassName => (Object)$variantInstance pairs */ public static function variants($class = null, $includeSubclasses = true) { if (!$class) { if (self::$variants === null) { $classes = ClassInfo::subclassesFor('SearchVariant'); $concrete = array(); foreach ($classes as $variantclass) { $ref = new ReflectionClass($variantclass); if ($ref->isInstantiable()) { $variant = singleton($variantclass); if ($variant->appliesToEnvironment()) { $concrete[$variantclass] = $variant; } } } self::$variants = $concrete; } return self::$variants; } else { $key = $class . '!' . $includeSubclasses; if (!isset(self::$class_variants[$key])) { self::$class_variants[$key] = array(); foreach (self::variants() as $variantclass => $instance) { if ($instance->appliesTo($class, $includeSubclasses)) { self::$class_variants[$key][$variantclass] = $instance; } } } return self::$class_variants[$key]; } }
public function test__construct() { $metadata = new ClassMetadata(__NAMESPACE__ . '\\ModelTest'); $metadata->addModel('entity', __NAMESPACE__ . '\\EntityTest'); $metadata->setIdentifier('entity', 'id'); $metadataFactory = $this->getMock('Pok\\PoolDBM\\Mapping\\ClassMetadataFactory', array('getMetadataFor', 'setModelManager')); $metadataFactory->expects($this->any())->method('getMetadataFor')->will($this->returnValue($metadata)); $refl = new \ReflectionClass('Pok\\PoolDBM\\Manager\\BaseManager'); $this->assertTrue($refl->isInstantiable()); $pool = new Pool(); $pool->addManager('entity', new EntityManager()); $manager = new TestManager(__NAMESPACE__ . '\\ModelTest', new ModelManager($pool, $metadataFactory)); $this->assertInstanceOf('Pok\\PoolDBM\\ModelRepository', $manager->getRepository($manager)); $this->assertInstanceOf(__NAMESPACE__ . '\\ModelTest', $manager->create()); $manager->save(new ModelTest()); $manager->save(new ModelTest(), true); try { $manager->save(new \stdClass()); } catch (\RuntimeException $e) { $this->assertEquals('Manager "Pok\\PoolDBM\\Tests\\Manager\\TestManager" is unable to save model "stdClass"', $e->getMessage()); } $manager->clear(); $this->assertInstanceOf(__NAMESPACE__ . '\\ModelTest', $manager->find(null)); $this->assertEquals(1, count($manager->findBy(array()))); $this->assertInstanceOf(__NAMESPACE__ . '\\ModelTest', $manager->findOneBy(array())); $this->assertEquals(1, count($manager->findAll())); }
public function load() { $queries = $this->path . '/queries.php'; $script = $this->path . '/script.php'; if (file_exists($queries)) { $sql = null; include $queries; if (is_array($sql)) { $this->queries = $sql; } } if (file_exists($script)) { include_once $script; $suffix = str_replace('-', '_', baseName($this->path)); $class = 'Nano_Migrate_Script_' . $suffix; if (class_exists($class, false)) { $reflection = new ReflectionClass($class); if ($reflection->isInstantiable() && $reflection->isSubclassOf('Nano_Migrate_Script')) { $this->script = $reflection->newInstance(); } else { $this->script = Nano_Migrate_ScriptEmpty::instance(); } } else { $this->script = Nano_Migrate_ScriptEmpty::instance(); } } else { $this->script = Nano_Migrate_ScriptEmpty::instance(); } }
public function fetchObject($className = "stdClass", $args = null) { $data = $this->fetchAll(); $callback = $args; if (!is_callable($callback) || $args === null) { // Кастомная обработка аргументов $callback = function ($data, $className, $args = null) { $items = []; $class = new \ReflectionClass($className); foreach ((array) $data as $item) { $values = []; if ($args === null) { $values = array_keys($data[0]); } else { foreach ((array) $args as $arg) { $values[] = $item[$arg]; } } // Создаем класс и передаем в конструктор значения выборки if ($class->isInstantiable()) { $items[] = $class->newInstanceArgs($values); } } return $items; }; } return $callback($this->ci, $data, $className, $args); }
public static function get($alias, $options = array(), $force_new = false) { if (isset(self::$singleton[$alias]) && !$force_new) { return self::$singleton[$alias]; } if (!isset(self::$map[$alias])) { return null; } $resolver = self::$map[$alias]['resolver']; if (is_string($resolver)) { $reflection = new \ReflectionClass($resolver); // Verifica si se puede instanciar la clase if (!$reflection->isInstantiable()) { throw new \Exception($alias . " The class is not instantiable"); } // Verifica si tiene un constructor $constructor = $reflection->getConstructor(); if (is_null($constructor)) { return new $resolver(); } $parameters = $constructor->getParameters(); if (count($parameters)) { throw new \Exception($alias . " The class requires parameters"); } } elseif ($resolver instanceof \Closure) { if (!is_array($options)) { echo "{$alias} {$options}"; } $object = $resolver($options); } if (self::$map[$alias]['new'] == false) { self::$singleton[$alias] = $object; } return $object; }
/** * Creates or gets an instance for class with class * * *Additional args* can be passed to this method. In this case they will be used to instantiate * the new class. If new class is instance of {@link AbsPluginSingleton} or {@link AbsCoreSingleton} * then additional args will be discarded. If class to be instantiated has $plugin property then the plugin * instance is added to the head of additional args. In that case the class constructor should have `Plugin $plugin` * argument first. * * **IMPORTANT** If class is instance of {@link AbsPluginSingleton} or {@link AbsCoreSingleton} then * {@link AbsPluginSingleton::getInstance()} or {@link AbsCoreSingleton::getInstance()} * is used. In that case any additional args will be discarded. If this is not the case then a new * instance of class is returned. * * @param string $className baseNamespace must be omitted. eg. `$className = 'MyBaseNamespaceChildren\MyClass' * * @return object An instance of [baseNamespace]\$className * @throws Exception If class not found or isn't instantiable or is plugin class has same name as one in core and * doesn't extend this core class. * @author Panagiotis Vagenas <*****@*****.**> * @since 0.0.2 */ public function createOrGet($className) { if ($this->existsInPlugin($className)) { if ($this->coreClassExists($className) && !$this->isCoreExtension($className)) { throw new Exception('Classes that have core name should ALWAYS extend core classes. Class name: ' . $className); } $class = $this->getPluginClassName($className); } elseif ($this->coreClassExists($className)) { $class = $this->getCoreClassName($className); } else { throw new Exception('Class ' . $className . ' doesn\'t seem to exists!'); } $args = func_get_args(); array_shift($args); $reflection = new \ReflectionClass($class); if (!$reflection || !($reflection->isSubclassOf($this->getCoreClassNameFromBase('Abs\\AbsPluginSingleton')) || $reflection->isSubclassOf($this->getCoreClassNameFromBase('Abs\\AbsCoreSingleton'))) && !$reflection->isInstantiable()) { throw new Exception('Trying to instantiate non-instantiable class ' . $class); } if ($reflection->isSubclassOf($this->getCoreClassNameFromBase('Abs\\AbsPluginSingleton'))) { /* @var AbsPluginSingleton $class */ $instance = $class::getInstance($this->plugin); } elseif ($reflection->isSubclassOf($this->getCoreClassNameFromBase('Abs\\AbsCoreSingleton'))) { /* @var AbsCoreSingleton $class */ $instance = $class::getInstance(); } else { if ($reflection->hasProperty('plugin') && (empty($args) || isset($args[0]) && !$args[0] instanceof Plugin)) { array_unshift($args, $this->plugin); } $instance = $reflection->newInstanceArgs($args); } return $instance; }
/** * @param string $base_class A parent class or interface. * @param bool $callback Optionally, don't call the register callback to construct the results array. * @param bool $use_constructor Optionally, get a class-instance via constructor - potentially UNSAFE! * @return array Array of result classes, optionally keyed. */ public function match($base_class, $callback = true, $use_constructor = false) { $results = array(); //foreach ($this as $class) { foreach ($this->classes as $class) { if (is_subclass_of($class, $base_class)) { if ($callback) { try { $obj = null; if ($use_constructor) { $obj = new $class(); } else { $reflect = new \ReflectionClass($class); // Ignore abstract classes. if ($reflect->isInstantiable()) { $obj = $reflect->newInstanceWithoutConstructor(); } } if ($obj) { $obj->{self::REGISTER_FN}($results); } } catch (\ReflectionException $e) { $this->debug('Warning! (RF) ' . $e->getMessage()); } catch (\Exception $e) { $this->debug('Warning! ' . $e->getMessage()); } //Was: $results[ $class::{ $callback }() ] = $class; } else { $results[] = $class; } } } return $results; }
/** * Whatever Data is returned by Hanlder, should be an array will be rendered as array on response * * @param AbstractUser $user * @param array $controllerInfo * @param String $handlerName */ function rx_interceptor_json($user, $controllerInfo, $handlerName) { $user->validate(); include_once RUDRA . "/core/handler/AbstractHandler.php"; $handlerInfo = ClassUtil::getHandler($handlerName); if ($handlerInfo != NULL) { global $temp; include_once $handlerInfo["filePath"]; $className = $handlerInfo["className"]; $tempClass = new ReflectionClass($className); if ($tempClass->isInstantiable()) { $temp = $tempClass->newInstance(); } if ($temp != NULL) { try { if ($tempClass->hasMethod("invokeHandler")) { $resp = call_method_by_class($tempClass, $temp, 'invokeHandler', array('user' => $user, 'data' => new RequestData(get_request_param("data"))), $handlerInfo["requestParams"]); if (isset($resp)) { echo json_encode($resp); } } } catch (Exception $e) { echo json_encode(array("error" => $e)); } } } }
/** * */ public function buildService($serviceCode, $definitions) { // Make sure the service has a definition if (array_key_exists($serviceCode, $definitions) === false) { \z\e(EXCEPTION_SERVICE_NOT_FOUND, ['serviceCode' => $serviceCode, 'definitions' => $definitions]); } // Get the definition $definition = $definitions[$serviceCode]; // If the definition is an object // Return it as such if (is_object($definition) === true) { return $definition; } // Otherwise, it's a classname $className = $definition; // Make sure the class exists if (class_exists($className) === false) { \z\e(EXCEPTION_SERVICE_NOT_FOUND, ['serviceCode' => $serviceCode, 'className' => $className]); } // Make sure the class is instantiable $reflection = new \ReflectionClass($className); if ($reflection->isInstantiable() === false) { \z\e(EXCEPTION_SERVICE_NOT_INSTANTIABLE, ['serviceCode' => $serviceCode, 'className' => $className]); } // Create the service $service = new $className(); return $service; }
/** * {@inheritdoc} */ public function dump(Definition $definition) { if (!$definition instanceof ObjectDefinition) { throw new \InvalidArgumentException(sprintf('This definition dumper is only compatible with ObjectDefinition objects, %s given', get_class($definition))); } $className = $definition->getClassName(); $classExist = class_exists($className) || interface_exists($className); // Class if (!$classExist) { $warning = '#UNKNOWN# '; } else { $class = new \ReflectionClass($className); $warning = $class->isInstantiable() ? '' : '#NOT INSTANTIABLE# '; } $str = sprintf(' class = %s%s', $warning, $className); // Scope $str .= PHP_EOL . " scope = " . $definition->getScope(); // Lazy $str .= PHP_EOL . " lazy = " . var_export($definition->isLazy(), true); if ($classExist) { // Constructor $str .= $this->dumpConstructor($className, $definition); // Properties $str .= $this->dumpProperties($definition); // Methods $str .= $this->dumpMethods($className, $definition); } return sprintf("Object (" . PHP_EOL . "%s" . PHP_EOL . ")", $str); }
public function invoke(User $user, $handlerName) { $class_info = Rudrax::classInfo($handlerName); $className = $class_info["class_name"]; $user->validate(); include_once RUDRA . "/core/handler/AbstractHandler.php"; include_once HANDLER_PATH . "/" . $className . ".php"; $tempClass = new ReflectionClass($className); global $temp; if ($tempClass->isInstantiable()) { $temp = $tempClass->newInstance(); } if ($temp != NULL) { if (is_subclass_of($temp, 'AbstractPageHandler')) { include_once RUDRA . "/core/handler/AbstractPageHandler.php"; } else { if (is_subclass_of($temp, 'AbstractTemplateHandler')) { include_once RUDRA . "/core/handler/AbstractTemplateHandler.php"; } else { if (is_subclass_of($temp, 'AbstractDataHandler')) { include_once RUDRA . "/core/handler/AbstractDataHandler.php"; } } } $temp->_invokeHandler($user, $handlerName, $tempClass); } }
private function buildTypeMap($paths) { global $prefs; $cacheKey = 'fieldtypes.' . $prefs['language']; if ($this->getPreCacheTypeMap()) { return; } $cachelib = TikiLib::lib('cache'); if ($data = $cachelib->getSerialized($cacheKey)) { $this->typeMap = $data['typeMap']; $this->infoMap = $data['infoMap']; $this->setPreCacheTypeMap($data); return; } foreach ($paths as $path => $prefix) { foreach (glob("{$path}/*.php") as $file) { if ($file === "{$path}/index.php") { continue; } $class = $prefix . substr($file, strlen($path) + 1, -4); $reflected = new ReflectionClass($class); if ($reflected->isInstantiable() && $reflected->implementsInterface('Tracker_Field_Interface')) { $providedFields = call_user_func(array($class, 'getTypes')); foreach ($providedFields as $key => $info) { $this->typeMap[$key] = $class; $this->infoMap[$key] = $info; } } } } uasort($this->infoMap, array($this, 'compareName')); $data = array('typeMap' => $this->typeMap, 'infoMap' => $this->infoMap); $cachelib->cacheItem($cacheKey, serialize($data)); $this->setPreCacheTypeMap($data); }
/** * Check if all classes given by the cli are instantiable. */ public function run() { $classNames = array_keys($this->_args); //No classes given if (!$classNames) { exit(1); } //Perform single checks for the classes foreach ($classNames as $className) { $reflectionClass = new ReflectionClass($className); //Is an interface? if ($reflectionClass->isInterface()) { echo "Interface"; exit(1); } //Is an abstract class? if ($reflectionClass->isAbstract()) { echo "Abstract"; exit(1); } //Is a trait? if ($reflectionClass->isTrait()) { echo "Trait"; exit(1); } //Can create the class with new? if (!$reflectionClass->isInstantiable()) { echo "Not instantiable"; exit(1); } } echo 'Done'; }
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; }
public function build($concrete, $parameters = array()) { //$concrete=字符串 则反射类 $reflector = new ReflectionClass($concrete); //类不存在会触发php类加载器 if (!$reflector->isInstantiable()) { #类不能被可实例化 $message = "Target [{$concrete}] is not instantiable."; throw new BindingResolutionException($message); } //反射出构造方法 ,返回ReflectionMethod 对象 $constructor = $reflector->getConstructor(); if (is_null($constructor)) { #不存在构造方法即没有直接定义__construct构造方法 //array_pop($this->buildStack); echo "没有直接定义__construct构造方法"; //直接实例化类 return new $concrete(); } //反射构造方法参数,没有参数则返回空数组,有参数则返回array(0=>第1个参数的ReflectionParameter对象,1=》第2个参数的ReflectionParameter对象) $dependencies = $constructor->getParameters(); $parameters = $this->keyParametersByArgument($dependencies, $parameters); $instances = $this->getDependencies($dependencies, $parameters); //var_dump($instances ); //从堆中移除 //array_pop($this->buildStack); //实例化类并返回对象,并把$instances参数给构造方法 return $reflector->newInstanceArgs($instances); }
/** * @param $key * @return mixed * @throws ReflectionException */ public function get($key) { if (empty($this->factories[$key]) && !empty($this->registry[$key])) { return $this->factories[$key] = $this->registry[$key](); } if (empty($this->instances[$key])) { if (!empty($this->registry[$key])) { $this->instances[$key] = $this->registry[$key](); } else { $reflected_class = new \ReflectionClass($key); if ($reflected_class->isInstantiable()) { $constructor = $reflected_class->getConstructor(); if ($constructor) { $parameters = $constructor->getParameters(); $constructor_parameters = []; foreach ($parameters as $parameter) { if ($parameter->getClass()) { $constructor_parameters[] = $this->get($parameter->getClass()->getName()); } else { $constructor_parameters[] = $parameter->getDefaultValue(); } } $this->instances[$key] = $reflected_class->newInstanceArgs($constructor_parameters); } else { $this->instances[$key] = $reflected_class->newInstance(); } } else { throw new ReflectionException('Class ' . $reflected_class->getName() . ' cannot be instantiable'); } } } return $this->instances[$key]; }
public function testEveryFieldTransformsDisabledAsClone() { $fieldClasses = ClassInfo::subclassesFor('FormField'); foreach ($fieldClasses as $fieldClass) { $reflectionClass = new ReflectionClass($fieldClass); if (!$reflectionClass->isInstantiable()) { continue; } $constructor = $reflectionClass->getMethod('__construct'); if ($constructor->getNumberOfRequiredParameters() > 1) { continue; } if ($fieldClass == 'CompositeField' || is_subclass_of($fieldClass, 'CompositeField')) { continue; } if ($fieldClass = 'NullableField') { $instance = new $fieldClass(new TextField("{$fieldClass}_instance")); } else { $instance = new $fieldClass("{$fieldClass}_instance"); } $isDisabledBefore = $instance->isDisabled(); $disabledInstance = $instance->performDisabledTransformation(); $this->assertEquals($isDisabledBefore, $instance->isDisabled(), "FormField class {$fieldClass} retains its disabled state after calling performDisabledTransformation()"); $this->assertTrue($disabledInstance->isDisabled(), "FormField class {$fieldClass} returns a valid disabled representation as of isDisabled()"); $this->assertNotSame($disabledInstance, $instance, "FormField class {$fieldClass} returns a valid cloned disabled representation"); } }