/** * Evaluate the callback and create an object instance if required and possible. * * @param array|callable $callback The callback to invoke. * * @return array|callable */ protected static function evaluateCallback($callback) { if (is_array($callback) && count($callback) == 2 && is_string($callback[0]) && is_string($callback[1])) { $class = new \ReflectionClass($callback[0]); // Ff the method is static, do not create an instance. if ($class->hasMethod($callback[1]) && $class->getMethod($callback[1])->isStatic()) { return $callback; } // Fetch singleton instance. if ($class->hasMethod('getInstance')) { $getInstanceMethod = $class->getMethod('getInstance'); if ($getInstanceMethod->isStatic()) { $callback[0] = $getInstanceMethod->invoke(null); return $callback; } } // Create a new instance. $constructor = $class->getConstructor(); if (!$constructor || $constructor->isPublic()) { $callback[0] = $class->newInstance(); } else { $callback[0] = $class->newInstanceWithoutConstructor(); $constructor->setAccessible(true); $constructor->invoke($callback[0]); } } return $callback; }
/** * Map collection by key. For objects, return the property, use * get method or is method, if avaliable. * * @param array $input Array of arrays or objects. * @param string $key Key to map by. * @throws \InvalidArgumentException If array item is not an array or object. * @throws \LogicException If array item could not be mapped by given key. * @return array Mapped array. */ public function mapBy(array $input, $key) { return array_map(function ($item) use($key) { if (is_array($item)) { if (!array_key_exists($key, $item)) { throw new \LogicException("Could not map item by key \"{$key}\". Array key does not exist."); } return $item[$key]; } if (!is_object($item)) { throw new \InvalidArgumentException("Item must be an array or object."); } $ref = new \ReflectionClass($item); if ($ref->hasProperty($key) && $ref->getProperty($key)->isPublic()) { return $item->{$key}; } if ($ref->hasMethod($key) && !$ref->getMethod($key)->isPrivate()) { return $item->{$key}(); } $get = 'get' . ucfirst($key); if ($ref->hasMethod($get) && !$ref->getMethod($get)->isPrivate()) { return $item->{$get}(); } $is = 'is' . ucfirst($key); if ($ref->hasMethod($is) && !$ref->getMethod($is)->isPrivate()) { return $item->{$is}(); } throw new \LogicException("Could not map item by key \"{$key}\". Cannot access the property directly or through getter/is method."); }, $input); }
/** * Call the initialization hooks. * * @param \Pimple $container The container that got initialized. * * @return void * * @throws \InvalidArgumentException When the hook method is invalid. * * @SuppressWarnings(PHPMD.Superglobals) * @SuppressWarnings(PHPMD.CamelCaseVariableName) */ protected function callHooks($container) { if (isset($GLOBALS['TL_HOOKS']['initializeDependencyContainer']) && is_array($GLOBALS['TL_HOOKS']['initializeDependencyContainer'])) { foreach ($GLOBALS['TL_HOOKS']['initializeDependencyContainer'] as $callback) { if (is_array($callback)) { $class = new \ReflectionClass($callback[0]); if (!$class->hasMethod($callback[1])) { if ($class->hasMethod('__call')) { $method = $class->getMethod('__call'); $args = array($callback[1], $container); } else { throw new \InvalidArgumentException(sprintf('No such Method %s::%s', $callback[0], $callback[1])); } } else { $method = $class->getMethod($callback[1]); $args = array($container); } $object = null; if (!$method->isStatic()) { $object = $this->getInstanceOf($callback[0]); } $method->invokeArgs($object, $args); } else { call_user_func($callback, $container); } } } }
public function testContracts() { $this->assertTrue($this->reflectedObject->isAbstract()); $this->assertTrue($this->reflectedObject->hasMethod('cleanVar')); $this->assertTrue($this->reflectedObject->hasMethod('getVar')); $this->assertInstanceOf('\\Xoops\\Core\\Text\\Sanitizer', \PHPUnit_Framework_Assert::readAttribute($this->object, 'ts')); }
public function testContracts() { $this->assertTrue($this->reflectedObject->isAbstract()); $this->assertTrue($this->reflectedObject->hasMethod('getDhtmlEditorSupport')); $this->assertTrue($this->reflectedObject->hasMethod('registerExtensionProcessing')); $this->assertTrue($this->reflectedObject->hasMethod('getEditorButtonHtml')); }
public function testHasMethods() { $reflection = new \ReflectionClass('\\Cekurte\\Environment\\Resource\\ResourceInterface'); $this->assertTrue($reflection->hasMethod('setResource')); $this->assertTrue($reflection->hasMethod('getResource')); $this->assertTrue($reflection->hasMethod('process')); }
public function load(Application $application) { $in = $this->container->getParameter('seed.directory'); //add seed:load and seed:unload commands $application->add($this->container->get('seed.load_seeds_command')); $application->add($this->container->get('seed.unload_seeds_command')); //Go through bundles and add *Seeds available in seed.directory foreach ($application->getKernel()->getBundles() as $bundle) { if (!is_dir($dir = sprintf('%s/%s', $bundle->getPath(), $in))) { continue; } $finder = new Finder(); $finder->files()->name('*Seed.php')->in($dir); $prefix = $bundle->getNameSpace() . '\\' . strtr($in, '/', '\\'); foreach ($finder as $file) { $ns = $prefix; if ($relativePath = $file->getRelativePath()) { $ns .= '\\' . strtr($relativePath, '/', '\\'); } $class = $ns . '\\' . $file->getBasename('.php'); $alias = 'seed.command.' . strtolower(str_replace('\\', '_', $class)); if ($this->container->has($alias)) { continue; } $r = new \ReflectionClass($class); if ($r->isSubclassOf('Soyuka\\SeedBundle\\Command\\Seed') && !$r->isAbstract() && ($r->hasMethod('load') || $r->hasMethod('unload'))) { $application->add($r->newInstanceArgs([$this->prefix, $this->separator])); } } } }
/** * Initializes the EventDispatcher-aware models. * * This methods has to accept unknown classes as it is triggered during * the boot and so will be called before running the propel:build command. */ public function initializeModels() { foreach ($this->classes as $id => $class) { $baseClass = sprintf('%s\\om\\Base%s', substr($class, 0, strrpos($class, '\\')), substr($class, strrpos($class, '\\') + 1, strlen($class))); try { $ref = new \ReflectionClass($baseClass); } catch (\ReflectionException $e) { $this->log(sprintf('The class "%s" does not exist.', $baseClass)); continue; } try { $ref = new \ReflectionClass($class); } catch (\ReflectionException $e) { $this->log(sprintf('The class "%s" does not exist. Either your model is not generated yet or you have an error in your listener configuration.', $class)); continue; } $canSetEventDispatcher = false; if (strpos($class, 'Query') !== false && $ref->hasMethod('setEventDispatcher') && $ref->hasMethod('getEventDispatcher')) { $canSetEventDispatcher = true; } elseif (strpos($class, 'Query') !== false) { $this->log(sprintf('The class "%s" does not implement "%s" and "%s" methods.', $class, 'setEventDispatcher', 'getEventDispatcher')); continue; } if (!$canSetEventDispatcher && !$ref->implementsInterface(self::MODEL_INTERFACE)) { $this->log(sprintf('The class "%s" does not implement "%s". Either your model is outdated or you forgot to add the EventDispatcherBehavior.', $class, self::MODEL_INTERFACE)); continue; } $class::setEventDispatcher(new LazyEventDispatcher($this->container, $id)); } }
/** * {@inheritdoc} */ public function process(ContainerBuilder $container) { foreach ($container->findTaggedServiceIds('mautic.model') as $id => $tags) { $definition = $container->findDefinition($id); $definition->addMethodCall('setEntityManager', [new Reference('doctrine.orm.entity_manager')]); $definition->addMethodCall('setSecurity', [new Reference('mautic.security')]); $definition->addMethodCall('setDispatcher', [new Reference('event_dispatcher')]); $definition->addMethodCall('setTranslator', [new Reference('translator')]); $definition->addMethodCall('setUserHelper', [new Reference('mautic.helper.user')]); $modelClass = $definition->getClass(); $reflected = new \ReflectionClass($modelClass); if ($reflected->hasMethod('setRouter')) { $definition->addMethodCall('setRouter', [new Reference('router')]); } if ($reflected->hasMethod('setLogger')) { $definition->addMethodCall('setLogger', [new Reference('monolog.logger.mautic')]); } if ($reflected->hasMethod('setSession')) { $definition->addMethodCall('setSession', [new Reference('session')]); } // Temporary, for development purposes if ($reflected->hasProperty('factory')) { $definition->addMethodCall('setFactory', [new Reference('mautic.factory')]); } } }
/** * Validates a callback more strictly and with more detailed errors. * * @param string|object|array $class A class name, object, function name, or array containing class/object and method * @param null|string $method If first param is class or object, the method name * @param string $error Error key returned by reference * @param bool $forceMethod If true, if no method is provided, never treat the class as a function * * @return bool * * @throws InvalidArgumentException */ public static function validateCallback($class, $method = null, &$error = null, $forceMethod = true) { if (is_array($class)) { if ($method) { throw new InvalidArgumentException('Method cannot be provided with class as array'); } $method = $class[1]; $class = $class[0]; } if ($forceMethod) { $method = strval($method); } else { if (!$method) { if (is_object($class)) { throw new InvalidArgumentException('Object given with no method'); } if (!function_exists($class)) { $error = 'invalid_function'; return false; } else { return true; } } } if (!is_string($method)) { throw new InvalidArgumentException('Method to check is not a string'); } if (!is_object($class)) { if (!$class || !class_exists($class)) { $error = 'invalid_class'; return false; } } $reflectionClass = new ReflectionClass($class); $isObject = is_object($class); if ($isObject && $reflectionClass->hasMethod('__call') || !$isObject && $reflectionClass->hasMethod('__callStatic')) { // magic method will always be called if a method can't be return true; } if (!$method || !$reflectionClass->hasMethod($method)) { $error = 'invalid_method'; return false; } $reflectionMethod = $reflectionClass->getMethod($method); if ($reflectionMethod->isAbstract() || !$reflectionMethod->isPublic()) { $error = 'invalid_method_configuration'; return false; } $isStatic = $reflectionMethod->isStatic(); if ($isStatic && $isObject) { $error = 'method_static'; return false; } else { if (!$isStatic && !$isObject) { $error = 'method_not_static'; return false; } } return true; }
/** */ public function testAddMethod() { $method = new ReflectionMethod('testMethod'); $this->assertFalse($this->object->hasMethod('testMethod')); $this->object->addMethod($method); $this->assertTrue($this->object->hasMethod('testMethod')); }
public function invoke(URLComponent $url) { $class_name = $url->getController(); $method = $url->getAction(); $class = $this->app . '\\action\\' . $class_name; //Response对象 $response = Response::getInstance(); //Request对象 $request = Request::getInstance(); #实例化控制器,使用反射 $reflection = new \ReflectionClass($class); $instacne = $reflection->newInstance(); //先执行初始化方法init if ($reflection->hasMethod('init')) { $init = $reflection->getMethod('init'); $data = $init->invokeArgs($instacne, array($request, $response)); if ($data) { //如果有返回数据则输出 $response->setBody($data); $response->send(); return true; } } if ($reflection->hasMethod($method)) { $method = $reflection->getMethod($method); } elseif ($reflection->hasMethod('getMiss')) { $method = $reflection->getMethod('getMiss'); } else { throw new RouteException('Method does not exist.'); } $data = $method->invokeArgs($instacne, array($request, $response)); #输出 $response->setBody($data); $response->send(); }
public static function make($name, $param = []) { $name = strtolower($name); if (isset(self::$wareHouse[$name . join(":", $param)])) { return self::$wareHouse[$name . join(":", $param)]; } if (!($service = Dependency::getService($name))) { Log::Error("The service \"{$name}\" dose not exist!"); throw new \Exception("The service \"{$name}\" dose not exist!", 1); } if (!class_exists($service)) { Log::Error("Class \" {$service}\" dose not exist!"); throw new \Exception("Class \" {$service}\" dose not exist!", 1); } $reflectClass = new \ReflectionClass($service); if ($reflectClass->hasMethod("newInstance")) { if (empty($param)) { return self::$wareHouse[$name] = call_user_func([$service, "newInstance"]); } else { return self::$wareHouse[$name . join(":", $param)] = call_user_func_array([$service, "newInstance"], $param); } } if ($constructor = $reflectClass->hasMethod("__construct")) { if ($constructor->isPublic()) { return self::$wareHouse[$name . join(":", $param)] = $reflectClass->newInstanceArgs($param); } } throw new \Exception("Class \" {$service} \" has no public contructor ", 1); }
/** * @dataProvider getClass */ public function testGetterAndSetter($class, $constructorParameterList) { $reflexionClass = new \ReflectionClass($class); if ($reflexionClass->getConstructor()) { $instance = $reflexionClass->newInstanceArgs($constructorParameterList); } else { $instance = $reflexionClass->newInstance(); } $propertyList = $reflexionClass->getProperties(); foreach ($propertyList as $property) { $name = ucfirst($property->getName()); $property->setAccessible(true); $getter = 'get' . $name; $setter = 'set' . $name; if ($reflexionClass->hasMethod($setter)) { $type = $this->guessParamType($reflexionClass->getMethod($setter)); if (isset($this->valueList[$type])) { $value = $this->valueList[$type]; $instance->{$setter}($value[0]); // test setter $this->assertEquals($property->getValue($instance), $value[0]); if ($reflexionClass->hasMethod($getter)) { $property->setValue($instance, $value[1]); // test getter $this->assertEquals($instance->{$getter}(), $value[1]); } } } } }
/** * Initialize preferences * * @access public * @param array * @return void */ public function initialize(array $config = array(), $reset = TRUE) { $reflection = new ReflectionClass($this); if ($reset === TRUE) { $defaults = $reflection->getDefaultProperties(); foreach (array_keys($defaults) as $key) { if ($key[0] === '_') { continue; } if (isset($config[$key])) { if ($reflection->hasMethod('set_' . $key)) { $this->{'set_' . $key}($config[$key]); } else { $this->{$key} = $config[$key]; } } else { $this->{$key} = $defaults[$key]; } } } else { foreach ($config as $key => &$value) { if ($key[0] !== '_' && $reflection->hasProperty($key)) { if ($reflection->hasMethod('set_' . $key)) { $this->{'set_' . $key}($value); } else { $this->{$key} = $value; } } } } // if a file_name was provided in the config, use it instead of the user input // supplied file name for all uploads until initialized again $this->_file_name_override = $this->file_name; return $this; }
/** * {@inheritdoc} */ public function validate(SchemaDescriptor $a, SchemaDescriptor $b) { /** @var FieldDescriptor[] $currentFields */ /** @var FieldDescriptor[] $inheritedFields */ $currentFields = $a->getFields(); $inheritedFields = $a->getInheritedFields(); $diff = array_intersect(array_keys($currentFields), array_keys($inheritedFields)); if (count($diff)) { /** @var \ReflectionClass $ref */ $ref = new \ReflectionClass(new FieldDescriptor('reflection', ['type' => 'string'])); foreach ($diff as $name) { foreach ($ref->getProperties() as $property) { // skip if (in_array($property->getName(), ['default', 'overridable', 'description', 'languages', 'deprecated'])) { continue; } $method = 'get' . ucfirst($property->getName()); if (!$ref->hasMethod($method)) { $method = 'is' . ucfirst($property->getName()); if (!$ref->hasMethod($method)) { continue; } } /** @var FieldDescriptor $fa */ /** @var FieldDescriptor $fb */ $fa = $currentFields[$name]; $fb = $inheritedFields[$name]; if ($fa && $fb && $fa->{$method}() != $fb->{$method}()) { throw new \RuntimeException(sprintf('The schema "%s" field "%s" is invalid. See inherited mixin fields.', $a->getId()->toString(), $property->getName())); } } } } }
/** * @param string $method * @param array $arguments * @return $this * @throws \Phur\Builder\Exception */ public function __call($method, array $arguments) { if (!$this->productClass->hasMethod($method) && !$this->productClass->hasMethod('__call')) { throw new Exception($this->productClass->getName() . "::{$method}() is not callable!"); } $this->configuration[] = array($method, $arguments); return $this; }
/** * @test */ public function testCommon() { $reflection = new \ReflectionClass('Upwork\\API\\Interfaces\\Client'); $this->assertTrue($reflection->isInterface()); $this->assertTrue($reflection->hasMethod('auth')); $this->assertTrue($reflection->hasMethod('request')); $this->assertTrue($reflection->hasMethod('setupRequestToken')); }
/** * Getter * @param string $name AttributeName * @return mixed */ public function __get($name) { if ($this->_reflection->hasMethod('get' . $name)) { /** @var \ReflectionMethod $method */ $method = $this->_reflection->getMethod('get' . $name); $method->invoke($this); } }
public function testContracts() { $this->assertTrue($this->reflectedObject->isAbstract()); $this->assertTrue($this->reflectedObject->hasMethod('getDefaultConfig')); $this->assertTrue($this->reflectedObject->hasProperty('ts')); $this->assertTrue($this->reflectedObject->hasProperty('shortcodes')); $this->assertTrue($this->reflectedObject->hasProperty('config')); }
/** * @param string $method * @param array $arguments * @return mixed * @throws \RuntimeException */ public function __call($method, $arguments) { if ($this->reflectionClass->hasMethod($method)) { return $this->client->command(['Pure\\Command\\StorageCommand', $this->class, $this->name, $method, $arguments]); } else { throw new \RuntimeException("Class `{$this->class}` does not have method `{$method}`."); } }
/** * Determines if the given method and arguments match the configured method and argument matchers * in this object. Returns true on success, false otherwise. * * @param string $method * @param array $args * * @return boolean */ public function matches($method, array &$args) { $matches = false; if ($this->mockedClass->hasMethod($method)) { $reflMethod = $this->mockedClass->getMethod($method); $matches = $reflMethod->isAbstract(); } return $matches; }
public function testController() { $this->loadClassFromVfs("Controller/TheliaStudioTestModuleConfigController"); $reflection = new \ReflectionClass("TheliaStudioTestModule\\Controller\\TheliaStudioTestModuleConfigController"); // Test mother classes $this->assertTrue($reflection->isSubclassOf("TheliaStudioTestModule\\Controller\\Base\\TheliaStudioTestModuleConfigController")); $this->assertTrue($reflection->isSubclassOf("Thelia\\Controller\\Admin\\BaseAdminController")); $this->assertTrue($reflection->hasMethod("defaultAction")); $this->assertTrue($reflection->hasMethod("saveAction")); }
public function testPropelRefName() { $reflection = new \ReflectionClass('Test\\Model\\Item'); $this->assertTrue($reflection->hasMethod('getCategories'), 'Item has getCategories'); $this->assertTrue($reflection->hasMethod('getOneCategory'), 'Item has getOneCategory'); $reflection = new \ReflectionClass('Test\\Model\\ItemCategory'); $this->assertTrue($reflection->hasMethod('getItems')); //<objectRefRelationName>Items</objectRefRelationName> $this->assertTrue($reflection->hasMethod('getCategoryCrossItems')); //<objectRefRelationName>CategoryCrossItems</objectRefRelationName> }
public function call($name, array $args = []) { if (!$this->target->hasMethod($name)) { $message = sprintf('Method not found on object %s.', get_class($this->origin)); throw new BadMethodCallException($message); } $method = $this->target->getMethod($name); $method->setAccessible(true); $response = $method->invokeArgs($this->origin, $args); return $response; }
/** * 初始化控制器的对象 * @param $class 对象的命名空间 */ private function initObj($class) { $this->unixPath = str_replace("\\", "/", $class); if (!file_exists(PES_PATH . $this->unixPath . '.class.php')) { return false; } //使用反射机制,验证控制器方法和是否支持魔术方法是否存在 $reflectionClass = new \ReflectionClass($class); if ($reflectionClass->hasMethod(ACTION) === false && $reflectionClass->hasMethod('__call') === false) { return false; } $obj = new $class(); $a = ACTION; $obj->{$a}(); }
/** * Resolves the target of the route and returns a callable. * * @param mixed $target * @param array $construct_args * * @throws RuntimeException If the target is not callable * * @return callable */ private static function getCallable($target, array $construct_args) { if (is_string($target)) { //is a class "classname::method" if (strpos($target, '::') === false) { $class = $target; $method = '__invoke'; } else { list($class, $method) = explode('::', $target, 2); } if (!class_exists($class)) { throw new RuntimeException("The class {$class} does not exists"); } $fn = new \ReflectionMethod($class, $method); if (!$fn->isStatic()) { $class = new \ReflectionClass($class); $instance = $class->hasMethod('__construct') ? $class->newInstanceArgs($construct_args) : $class->newInstance(); $target = [$instance, $method]; } } //if it's callable as is if (is_callable($target)) { return $target; } throw new RuntimeException('The route target is not callable'); }
/** * Check to see if said module has method and is publically callable * @param {string} $module The raw module name * @param {string} $method The method name */ public function moduleHasMethod($module, $method) { $this->getActiveModules(); $module = ucfirst(strtolower($module)); if (!empty($this->moduleMethods[$module]) && in_array($method, $this->moduleMethods[$module])) { return true; } $amods = array(); foreach (array_keys($this->active_modules) as $mod) { $amods[] = $this->cleanModuleName($mod); } if (in_array($module, $amods)) { try { $rc = new \ReflectionClass($this->FreePBX->{$module}); if ($rc->hasMethod($method)) { $reflection = new \ReflectionMethod($this->FreePBX->{$module}, $method); if ($reflection->isPublic()) { $this->moduleMethods[$module][] = $method; return true; } } } catch (\Exception $e) { } } return false; }
/** * Get class constructor * * @param \ReflectionClass $class * @param bool $groupByPosition * @param bool $inherited * @return array */ public function getConstructorArguments(\ReflectionClass $class, $groupByPosition = false, $inherited = false) { $output = array(); /** * Skip native PHP types, classes without constructor */ if (!$class->getFileName() || false == $class->hasMethod('__construct') || !$inherited && $class->getConstructor()->class != $class->getName()) { return $output; } foreach ($class->getConstructor()->getParameters() as $parameter) { $name = $parameter->getName(); $position = $parameter->getPosition(); $parameterClass = $parameter->getClass(); $type = $parameterClass ? '\\' . $parameterClass->getName() : ($parameter->isArray() ? 'array' : null); $index = $groupByPosition ? $position : $name; $default = null; if ($parameter->isOptional()) { if ($parameter->isDefaultValueAvailable()) { $value = $parameter->getDefaultValue(); if (true == is_array($value)) { $default = $this->_varExportMin($value); } elseif (true == is_int($value)) { $default = $value; } else { $default = is_null($parameter->getDefaultValue()) ? 'null' : "'" . $parameter->getDefaultValue() . "'"; } } elseif ($parameter->allowsNull()) { $default = 'null'; } } $output[$index] = array('name' => $name, 'position' => $position, 'type' => $type, 'isOptional' => $parameter->isOptional(), 'default' => $default); } return $output; }
/** * Find classes which are used as parameters types of the specified method and are not declared. * * @param string $file * @param \ReflectionClass $classReflection * @param string $methodName * @param string $entityType * @return string[] */ protected function _findMissingClasses($file, $classReflection, $methodName, $entityType) { $missingClasses = []; if ($classReflection->hasMethod($methodName)) { $constructor = $classReflection->getMethod($methodName); $parameters = $constructor->getParameters(); /** @var $parameter \ReflectionParameter */ foreach ($parameters as $parameter) { preg_match('/\[\s\<\w+?>\s([\w\\\\]+)/s', $parameter->__toString(), $matches); if (isset($matches[1]) && substr($matches[1], -strlen($entityType)) == $entityType) { $missingClassName = $matches[1]; try { if (class_exists($missingClassName)) { continue; } } catch (\Magento\Framework\Exception\LocalizedException $e) { } $sourceClassName = $this->getSourceClassName($missingClassName, $entityType); if (!class_exists($sourceClassName) && !interface_exists($sourceClassName)) { $this->_log->add( Log::CONFIGURATION_ERROR, $missingClassName, "Invalid {$entityType} for nonexistent class {$sourceClassName} in file {$file}" ); continue; } $missingClasses[] = $missingClassName; } } } return $missingClasses; }