public function evaluate($configFiles) { $routeDefinitions = $this->parse($configFiles); $routes = array(); $limit = count($this->routes) > 0; foreach ($routeDefinitions as $name => $route) { // we only load routes defined in the app.yml from if ($limit && !in_array($this->getOriginalName($name), $this->routes)) { continue; } $r = new ReflectionClass($route[0]); if ($r->isSubclassOf('sfRouteCollection')) { $route[1][0]['requirements']['sw_app'] = $this->app; $route[1][0]['requirements']['sw_host'] = $this->host; $collection_route = $r->newInstanceArgs($route[1]); foreach ($collection_route->getRoutes() as $name => $route) { $routes[$this->app . '.' . $name] = new swEncapsulateRoute($route, $this->host, $this->app); } } else { $route[1][2]['sw_app'] = $this->app; $route[1][2]['sw_host'] = $this->host; $routes[$name] = new swEncapsulateRoute($r->newInstanceArgs($route[1]), $this->host, $this->app); } } return $routes; }
public static function getModuleInstanceByTypeAndName($sType, $sName) { if (!$sName) { throw new Exception("Exception in Module::getModuleInstanceByTypeAndName(): module name is empty"); } $sClassName = self::getClassNameByTypeAndName($sType, $sName); if (!self::isModuleEnabled($sType, $sName)) { throw new Exception("Exception in Module::getModuleInstanceByTypeAndName(): tried to instanciate disabled module {$sType}.{$sName}"); } $aArgs = array_slice(func_get_args(), 2); $oClass = new ReflectionClass($sClassName); if ($sClassName::isSingleton()) { if (!isset(self::$SINGLETONS[$sClassName])) { try { self::$SINGLETONS[$sClassName] = $oClass->newInstanceArgs($aArgs); } catch (ReflectionException $ex) { self::$SINGLETONS[$sClassName] = $oClass->newInstance(); } } return self::$SINGLETONS[$sClassName]; } try { return $oClass->newInstanceArgs($aArgs); //Does not work in PHP < 5.1.3 } catch (ReflectionException $ex) { return $oClass->newInstance(); //Does not work in PHP < 5.1.3 } }
/** * 调用具体的业务逻辑接口,通常来说是项目中的 * controller,也可以RPC调用 * @param Request $request * @return mixed * @throws \Simple\Application\Game\Cycle\Exception\GameCycleException */ public function toCall(Request $request) { $head = $request->getHeader(); $module = ucfirst($head[0]); $action = $head[1]; // TODO 获取类的命名空间 $cls = new \ReflectionClass(APP_TOP_NAMESPACE . '\\Controller\\' . $module . 'Controller'); $instance = null; //优先调用init方法 if ($cls->hasMethod('__init__')) { $initMethod = $cls->getMethod('__init__'); if ($initMethod->isPublic() == true) { $instance = $cls->newInstanceArgs(array()); $initMethod->invokeArgs($instance, array()); } } $method = $cls->getMethod($action); if ($method->isPublic() == false) { throw new GameCycleException('无法调用接口:' . $module . '.' . $action); } if ($instance == null) { $instance = $cls->newInstanceArgs(array()); } $ret = $method->invokeArgs($instance, array($request)); if ($ret instanceof Response === false) { throw new GameCycleException('接口返回的对象必须为:Response对象。'); } return $ret; }
/** * @param array|null $args * * @return object */ function invoke(array $args = null) { if ($args !== null) { return $this->reflectionClass->newInstanceArgs($args); } return $this->reflectionClass->newInstance(); }
public function create($component, array $args = [], $forceNewInstance = false, $share = []) { if (!$forceNewInstance && isset($this->instances[$component])) { return $this->instances[$component]; } if (empty($this->cache[$component])) { $rule = $this->getRule($component); $class = new \ReflectionClass($rule->instanceOf ? $rule->instanceOf : $component); $constructor = $class->getConstructor(); $params = $constructor ? $this->getParams($constructor, $rule) : null; $this->cache[$component] = function ($args) use($component, $rule, $class, $constructor, $params, $share) { if ($rule->shared) { if ($constructor) { try { $this->instances[$component] = $object = $class->newInstanceWithoutConstructor(); $constructor->invokeArgs($object, $params($args, $share)); } catch (\ReflectionException $r) { $this->instances[$component] = $object = $class->newInstanceArgs($params($args, $share)); } } else { $this->instances[$component] = $object = $class->newInstanceWithoutConstructor(); } } else { $object = $params ? $class->newInstanceArgs($params($args, $share)) : new $class->name(); } if ($rule->call) { foreach ($rule->call as $call) { $class->getMethod($call[0])->invokeArgs($object, call_user_func($this->getParams($class->getMethod($call[0]), $rule), $this->expand($call[1]))); } } return $object; }; } return $this->cache[$component]($args); }
public static function create($arg1, $arg2 = null) { if ($arg1 instanceof AbstractValidator) { return $arg1; } if (is_array($arg1) && !isset($arg1['class'])) { return self::createGroup($arg1); } if (is_string($arg1)) { $class = $arg1; $options = $arg2; } else { $class = $arg1['class']; if (isset($arg1['options'])) { $options = $arg1['options']; } } $reflection = new \ReflectionClass($class); if (isset($options)) { $validator = $reflection->newInstanceArgs($options); } else { $validator = $reflection->newInstanceArgs(); } return $validator; }
/** * Populates a set of models with the data from end user. * This method is mainly used to collect tabular data input. * The data to be loaded for each model is `$data[formName][index]`, where `formName` * refers to the sort name of model class, and `index` the index of the model in the `$data` array. * If `$formName` is empty, `$data[index]` will be used to populate each model. * The data being populated to each model is subject to the safety check by [[setAttributes()]]. * @param string $class Model class name. * @param array $data the data array. This is usually `$_POST` or `$_GET`, but can also be any valid array * supplied by end user. * @param string $formName the form name to be used for loading the data into the models. * If not set, it will use the sort name of called class. * @param Model[] $origin original models to be populated. It will be check using `$keys` with supplied data. * If same then will be used for result model. * @param array $options Option to model * - scenario for model. * - arguments The parameters to be passed to the class constructor as an array. * @return boolean|Model[] whether at least one of the models is successfully populated. */ public static function createMultiple($class, $data, $formName = null, &$origin = [], $options = []) { $reflector = new \ReflectionClass($class); $args = isset($options['arguments']) ? $options['arguments'] : []; if ($formName === null) { /* @var $model Model */ $model = empty($args) ? new $class() : $reflector->newInstanceArgs($args); $formName = $model->formName(); } if ($formName != '') { $data = isset($data[$formName]) ? $data[$formName] : null; } if ($data === null) { return false; } $models = []; foreach ($data as $i => $row) { $model = null; if (isset($origin[$i])) { $model = $origin[$i]; unset($origin[$i]); } else { $model = empty($args) ? new $class() : $reflector->newInstanceArgs($args); } if (isset($options['scenario'])) { $model->scenario = $options['scenario']; } $model->load($row, ''); $models[$i] = $model; } return $models; }
/** * Test the Notice->similar_to(<Notice>) method * * @test * @dataProvider providerSimilarTo */ public function testSimilarTo($args_one, $args_two, $expected) { $reflected = new ReflectionClass('Notice'); $notice_one = $reflected->newInstanceArgs($args_one); $notice_two = $reflected->newInstanceArgs($args_two); $this->assertSame($expected, $notice_one->similar_to($notice_two)); }
public function testGetAllowed() { $options = new ParserOptions(); $options->allowed_tags = ['noparse', 'code', 'img']; $method = $this->reflectionClass->getMethod('getAllowed'); $this->parser = $this->reflectionClass->newInstanceArgs([$options]); $this->assertEquals(['code', 'img', 'noparse'], $method->invoke($this->parser)); }
/** * Construct new class by class name * @param string $className class that want to be constructed. * @param array $args Constructor params if exist * @return object Constructed Class */ public static function constructClass($className, array $args = array()) { $reflector = new \ReflectionClass($className); if ($reflector->hasMethod('__construct') && count($args) > 0) { return $reflector->newInstanceArgs($args); } return $reflector->newInstanceArgs(); }
/** * @param array $args * * @return \IntlDateFormatter */ protected static function createInstance(array $args = array()) { if (!self::$reflection) { self::$reflection = new \ReflectionClass('IntlDateFormatter'); } $instance = self::$reflection->newInstanceArgs($args); self::checkInternalClass($instance, '\\IntlDateFormatter', $args); return $instance; }
/** * Метод формирует экземпляр класса на основе строки. * После будет применён фильтр, если он есть. * * @return object */ private function getInst(array $row) { if ($this->constructorParams) { $args = $this->constructorParams; $args[] = $row; return $this->RC->newInstanceArgs($args); } else { return $this->RC->newInstance($row); } }
/** * {@inheritdoc} */ public function create(array $arguments = []) { if (empty($arguments[0])) { $arguments[0] = $this->createEntity(); } if (!$this->modelClassReflection) { $this->modelClassReflection = new \ReflectionClass($this->modelClassName); } return $this->modelClassReflection->newInstanceArgs($arguments); }
/** * @param $class * @param $args * @return object */ private static function instantiate($class, $args) { //BOOOOO, this produces a parse error on less than 5.6.0 // if (version_compare(phpversion(), '5.6.0') !== -1) { // $instance = new $class(...$args); // } else { $reflect = new \ReflectionClass($class); $instance = $args === null || $args === false ? $reflect->newInstanceArgs() : $reflect->newInstanceArgs($args); // } return $instance; }
public function create($class, array $args = array()) { $this->validate($class, $args); $reflection = new \ReflectionClass($class); if ($reflection->getConstructor()) { $object = $reflection->newInstanceArgs($args); } else { $object = $reflection->newInstanceArgs(); } return $object; }
/** * @param string $interface * @param array $params * @return object */ public function make($interface, array $params = array()) { $this->validate($interface); if ($this->has($interface) === false) { throw new \InvalidArgumentException("You should register {$interface} in the Factory first."); } $reflected = new \ReflectionClass($this->map[$interface]); if (empty($params)) { return $reflected->newInstanceArgs(); } return $reflected->newInstanceArgs($params); }
/** * @param OutputInterface $output The output interface * @param integer $level The minimum logging level at which this handler will be triggered * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not */ public function __construct(OutputInterface $output, $level = Logger::DEBUG, $bubble = true) { parent::__construct($level, $bubble); $this->output = $output; foreach ($this->styleMap as $name => $styles) { $style = new \ReflectionClass('Symfony\\Component\\Console\\Formatter\\OutputFormatterStyle'); $this->output->getFormatter()->setStyle($name, $style->newInstanceArgs($styles)); if ($this->output instanceof ConsoleOutputInterface) { $this->output->getErrorOutput()->getFormatter()->setStyle($name, $style->newInstanceArgs($styles)); } } }
/** * Instantiates an object using a string formatted according to the Google * Analytics API's syntax. * * @param string $filters * @return Google\Analytics\GaDataFilterCollection */ public static function createFromString($filters) { $andFilters = \PFXUtils::explodeUnescaped(self::OP_AND, $filters); $andCollections = array(); $reflector = new \ReflectionClass(__CLASS__); foreach ($andFilters as $andFilter) { $orFilters = \PFXUtils::explodeUnescaped(self::OP_OR, $andFilter); $orFilterInstances = array(); foreach ($orFilters as $orFilter) { $orFilterInstances[] = new GaDataConditionalExpression($orFilter); } $andCollections[] = $reflector->newInstanceArgs(array_merge(array(self::OP_OR), $orFilterInstances)); } return $reflector->newInstanceArgs(array_merge(array(self::OP_AND), $andCollections)); }
public static function load($model, $id = null, $params = array(), $host = null) { $storage_object = null; $reflect = new \ReflectionClass(self::getClass($model)); if (sizeof($params)) { $storage_object = $reflect->newInstanceArgs($params); } else { $storage_object = $reflect->newInstanceArgs(); } if (in_array('Empathy\\MVC\\Entity', class_parents($storage_object))) { self::connectModel($storage_object, $host); $storage_object->init(); } return $storage_object; }
/** * Creates a new instance for the class */ public static function createInstance($className, $args = []) { $reflection = new \ReflectionClass($className); if ($reflection->implementsInterface('App\\Interfaces\\SingletonInterface')) { if (isset(self::$singletones[$className])) { return self::$singletones[$className]; } else { $instance = $args ? $reflection->newInstanceArgs($args) : $reflection->newInstance(); self::$singletones[$className] = $instance; } } else { $instance = $args ? $reflection->newInstanceArgs($args) : $reflection->newInstance(); } return $instance; }
public function configureService($serviceName, array $settings) { $this->app[$serviceName] = $this->app->share(function (WebApplication $app) use($settings) { $class = new \ReflectionClass($settings['class']); $arguments = array(); $deps = isset($settings['deps']) ? $settings['deps'] : array(); foreach ($deps as $key) { if (is_string($key) && preg_match('/^%(.+)%$/', $key, $matches)) { $key = $matches[1]; $value = $this->app[$key]; } else { $value = $key; } $arguments[] = $value; } $instance = $class->newInstanceArgs($arguments); if (isset($settings['set'])) { foreach ($settings['set'] as $field => $value) { if (is_string($value) && preg_match('/^%(.+)%$/', $value, $matches)) { $value = $matches[1]; $value = $this->app[$value]; } $method = 'set' . ucwords(preg_replace('/_+/', ' ', strtolower($field))); $method = preg_replace('/\\s+/', '', $method); $instance->{$method}($value); } } return $instance; }); }
/** * Creates and returns a new instance of the data item. * * @since 1.8 * * @return SMWDataItem */ public function newInstance() { $reflector = new \ReflectionClass($this->getClass()); $args = func_get_args(); $instance = $reflector->newInstanceArgs($args); return $instance; }
/** * 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'); }
/** * Creates an object instance of the requested class, optionally passing additional constructor arguments * * @param $requestedClass * @param ...$arguments * @return mixed|object */ public final function getInstance($requestedClass, ...$arguments) { if (isset($this->singletons[$requestedClass])) { return $this->singletons[$requestedClass]; } $useSingleton = false; // Check for singletons first as they should trump previous registrations of non // singleton mappings. if (isset($this->concreteClassMappings['_' . $requestedClass])) { $class = $this->concreteClassMappings['_' . $requestedClass]; $useSingleton = true; } elseif (isset($this->concreteClassMappings[$requestedClass])) { $class = $this->concreteClassMappings[$requestedClass]; } else { $class = $requestedClass; } $reflection = new \ReflectionClass($class); if ($reflection->isAbstract()) { throw new ClassMappingException($class); } $constructor = $reflection->getConstructor(); if ($constructor == null) { // No defined constructor so exit simply with a new instance. $instance = $reflection->newInstanceArgs($arguments); } else { $instance = $this->generateInstanceFromConstructor($reflection, $constructor, $arguments); } if ($useSingleton) { $this->singletons[$requestedClass] = $instance; } return $instance; }
/** * Factory method for create object of agent class. * * Bitrix calls this method to run agent. Your agents should be registered through * `\Notamedia\ConsoleJedi\Agent\AgentTask`. All arguments from this method should * be duplicated in the object constructor: * * `agent($arg1, …, $arg2)` → `__construct($arg1, …, $arg2)`. * * @return static * * @see AgentTask */ public static function agent() { static::$constructorArgs = func_get_args(); static::$agentMode = true; $reflection = new \ReflectionClass(get_called_class()); return $reflection->newInstanceArgs(static::$constructorArgs); }
public static function resolve($type, $constructorArguments = []) { $resolvedClass = self::getResolvedClassName($type); if ($resolvedClass === null) { throw new exceptions\ResolutionException("Could not resolve dependency {$type}"); } $reflection = new \ReflectionClass($resolvedClass); if ($reflection->isAbstract()) { throw new exceptions\ResolutionException("Abstract class {$reflection->getName()} cannot be instantiated. " . "Please provide a binding to an implementation."); } $constructor = $reflection->getConstructor(); $instanceParameters = []; if ($constructor != null) { $parameters = $constructor->getParameters(); foreach ($parameters as $parameter) { $class = $parameter->getClass(); if (isset($constructorArguments[$parameter->getName()])) { $instanceParameters[] = $constructorArguments[$parameter->getName()]; } else { $instanceParameters[] = $class ? self::resolve($class->getName()) : null; } } } return $reflection->newInstanceArgs($instanceParameters); }
/** * Constructor * * @param string|object $base_class Class name of the base class, or an instance * @param array $constructor_args (Optional) Arguments to pass to the constructor of the base class * @param array $constants (Optional) Constants to override */ public function __construct($base_class, array $constructor_args = array(), array $constants = array()) { // @codeCoverageIgnoreStart if (PHP_VERSION_ID < 50300) { trigger_error(get_class() . ': This class requires PHP version 5.3 or higher.', E_USER_ERROR); } // @codeCoverageIgnoreEnd if (is_object($base_class) && count($constructor_args)) { throw new Mollie_Testing_Exception('Unused constructor arguments for passed instance of "' . get_class($base_class) . '".'); } // If it's an instance, just accept it if (is_object($base_class)) { $this->_base_class = $base_class; } elseif (!class_exists($base_class)) { throw new Mollie_Testing_Exception("Base class '{$base_class}' does not exist."); } else { $ref = new ReflectionClass($base_class); if ($ref->isAbstract()) { $ref = new ReflectionClass($this->createDerivedClass($base_class)); } if ($ref->getConstructor() && count($constructor_args) < $ref->getConstructor()->getNumberOfRequiredParameters()) { throw new Mollie_Testing_Exception($ref->getConstructor()->getNumberOfRequiredParameters() . " constructor arguments required for '{$base_class}::__construct(...)'."); } $this->_base_class = sizeof($constructor_args) ? $ref->newInstanceArgs($constructor_args) : $ref->newInstance(); } }
/** * Loads the given file and then creates a new instance of the class name * given (the intention being that the class was inside the file). * * An instance of the class will be set to the controller associated with * this loader. * * If ommitted then the class and variable names will be presumed to be * the name of the file being opnened. * * Any variables after the className are passed into the constructor of * the class when it is created. * * @param file The file to open. * @param varName The name of the variable to set the file to, or null to omit. * @param className The name of the class to initialize, or null to omit. */ public function obj($file, $varName = null, $className = null) { $last = strrpos($file, '/'); if ($last === false) { $fileStr = $file; } else { $fileStr = substr($file, $last + 1); } if ($className !== null) { $className = trim($className); } if ($className === null || $className === '') { $className = $fileStr; } if ($varName !== null) { $varName = trim($varName); } if ($varName === null || $varName === '') { $varName = strtolower($className); } $this->load($file); // stored so models can get access to this obj Loader::$currentController = $this->parentObj; // if has parameters for the object being made if (func_num_args() > 3) { $params = array_slice(func_get_args(), 3); $reflection = new ReflectionClass($className); $obj = $reflection->newInstanceArgs($params); } else { $obj = new $className(); } Loader::$currentController = null; $this->parentObj->{$varName} = $obj; return $obj; }
public static function doLog($logmethod, array $data, &$output) { $log = new Logger('ezperflogger'); // constructor args for the specific handler can be set via ini /// @todo how to create resources instead? foreach (eZPerfLoggerINI::variable('MonologSettings', 'LogHandlers') as $handlerName) { $handlerClass = 'Monolog\\Handler\\' . $handlerName . "Handler"; if (eZPerfLoggerINI::hasVariable('MonologSettings', 'LogHandler_' . $handlerName)) { $r = new ReflectionClass($handlerClass); $handler = $r->newInstanceArgs(eZPerfLoggerINI::variable('MonologSettings', 'LogHandler_' . $handlerName)); } else { $handler = new $handlerClass(); } $log->pushHandler($handler); } // the default severity level: taken from config file $level = (int) eZPerfLoggerINI::variable('MonologSettings', 'SeverityLevel'); // either coalesce messages or not: taken from config file if (eZPerfLoggerINI::variable('MonologSettings', 'Coalescevariables') == 'enabled') { /// @todo allow via ini file the specification of custom formatters? $msg = array(); foreach ($data as $varname => $value) { $msg[] = "{$varname}: {$value}"; } $log->addRecord($level, implode(', ', $msg)); } else { foreach ($data as $varname => $value) { $log->addRecord($level, "{$varname}: {$value}"); } } }
/** * @param string $className the class to instantiate * @param array ...$args any number of constructor arguments * @return mixed */ public function instantiate($className, ...$args) { $class = new \ReflectionClass($className); $instance = $class->newInstanceArgs($args); foreach ($this->reader->getProperties($className) as $name => $config) { try { $property = $class->getProperty($name); } catch (\ReflectionException $e) { throw new \RuntimeException(sprintf('Unable to read the property "%s" for class "%s"', $name, $className)); } $field = $config['field'] ? $config['field'] : $name; // dot notation if ($this->enableDotNotation && preg_match('/\\./', $field)) { $originalValue = $this->resolve($field, null); } elseif (!isset($this->data[$field])) { continue; } else { $originalValue = $this->data[$field]; } $newValue = $this->createTypeClass($config, $originalValue)->getValue(); $property->setAccessible(true); $property->setValue($instance, $newValue); } return $instance; }