/** * 调用具体的业务逻辑接口,通常来说是项目中的 * 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; }
/** * 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); }
function doCall($method, $parameters, $instance, $serverKey) { $callParameters = validateCallParameters($method, $parameters, $instance); $reflectedClass = new ReflectionClass(get_class($instance)); $reflectedMethod = $reflectedClass->getMethod($method->getName()); $result; $result = $reflectedMethod->invokeArgs($instance, $callParameters); $resultJson = ""; //Print custom errors $reflectedErrorMethod = $reflectedClass->getMethod("getErrors"); $reflectedErrors = $reflectedErrorMethod->invoke($instance); if (!empty($reflectedErrors)) { $resultJson .= "["; foreach ($reflectedErrors as $reflectedError) { $reflectedErrorClass = new ReflectionClass(get_class($reflectedError)); $code = $reflectedErrorClass->getMethod("getCode")->invoke($reflectedError); $message = $reflectedErrorClass->getMethod("getMessage")->invoke($reflectedError); $resultJson .= '{"code":' . JsonUtils::encodeToJson($code) . ',"message":' . JsonUtils::encodeToJson($message) . '},'; } $resultJson = JsonUtils::removeLastChar($reflectedErrors, $resultJson); $resultJson .= "]"; } else { $resultJson .= serializeMethodResult($method, $result, $instance, $serverKey); } return $resultJson; }
public function call_function($function_name, $parameters) { if (!method_exists($this, $function_name)) { return false; } $reflector = new ReflectionClass($this); if (count($parameters) < $reflector->getMethod($function_name)->getNumberOfRequiredParameters()) { return false; } $collapse_parameters = false; $function_parameters = $reflector->getMethod($function_name)->getParameters(); if (count($function_parameters) && end($function_parameters)->name == 'parameters') { $collapse_parameters = true; } if (count($parameters) > count($function_parameters) && !$collapse_parameters) { return false; } if ($collapse_parameters) { $non_optional = array_splice($parameters, 0, count($function_parameters) - 1); if (count($parameters)) { $parameters = array_merge($non_optional, array($parameters)); } else { $parameters = $non_optional; } } return call_user_func_array(array($this, $function_name), $parameters); }
public static function getControllerMethod($bgp_module_name, $public_method) { $method_definition = array(); if (!empty($bgp_module_name) && !empty($public_method)) { $bgp_controller_name = 'BGP_Controller_' . ucfirst(strtolower($bgp_module_name)); if (is_subclass_of($bgp_controller_name, 'BGP_Controller')) { // Reflection $reflector = new ReflectionClass($bgp_controller_name); $method = $reflector->getMethod($public_method); $name = $method->name; $class = $method->class; $doc = $reflector->getMethod($name)->getDocComment(); // Parse Doc if (is_string($doc)) { $doc = new DocBlock($doc); $desc = $doc->description; $params = $doc->all_params; // Params if (!empty($params['param'])) { $args = $params['param']; } else { $args = array(); } $http = $params['http_method'][0]; $resource = $params['resource'][0]; $response = $params['return'][0]; $method_definition = array('resource' => trim($resource), 'id' => trim($public_method), 'name' => trim($http), 'description' => trim($desc), 'params' => $args, 'response' => trim($response)); } } } return $method_definition; }
/** * @return \ReflectionParameter */ protected function getMethodFirstParameter() { $backtrace = debug_backtrace(); $methodInfo = $this->reflection->getMethod($this->getName()); $parameters = $methodInfo->getParameters(); return $parameters[0]; }
/** * @author tonykova * @covers Jetpack_API_Plugins_Install_Endpoint */ public function test_Jetpack_API_Plugins_Install_Endpoint() { $endpoint = new Jetpack_JSON_API_Plugins_Install_Endpoint(array('stat' => 'plugins:1:new', 'method' => 'POST', 'path' => '/sites/%s/plugins/new', 'path_labels' => array('$site' => '(int|string) The site ID, The site domain'), 'request_format' => array('plugin' => '(string) The plugin slug.'), 'response_format' => Jetpack_JSON_API_Plugins_Endpoint::$_response_format, 'example_request_data' => array('headers' => array('authorization' => 'Bearer YOUR_API_TOKEN'), 'body' => array('plugin' => 'buddypress')), 'example_request' => 'https://public-api.wordpress.com/rest/v1/sites/example.wordpress.org/plugins/new')); $the_plugin_file = 'the/the.php'; $the_real_folder = WP_PLUGIN_DIR . '/the'; $the_real_file = WP_PLUGIN_DIR . '/' . $the_plugin_file; // Check if 'The' plugin folder is already there. if (file_exists($the_real_folder)) { $this->markTestSkipped('The plugn the test tries to install (the) is already installed. Skipping.'); } $class = new ReflectionClass('Jetpack_JSON_API_Plugins_Install_Endpoint'); $plugins_property = $class->getProperty('plugins'); $plugins_property->setAccessible(true); $plugins_property->setValue($endpoint, array($the_plugin_file)); $validate_plugins_method = $class->getMethod('validate_plugins'); $validate_plugins_method->setAccessible(true); $result = $validate_plugins_method->invoke($endpoint); $this->assertTrue($result); $install_plugin_method = $class->getMethod('install'); $install_plugin_method->setAccessible(true); $result = $install_plugin_method->invoke($endpoint); $this->assertTrue($result); $this->assertTrue(file_exists($the_real_folder)); // Clean up $this->rmdir($the_real_folder); }
/** * action method is execute action. * * @param string $name is action name * @param array $arguments for action */ public function action($name, $arguments = array()) { //switch canvas for action name... $this->_canvas->switchAction($name); // check authetication // if ($this->authentication($action); $this->_assign = array(); $ref = new ReflectionClass($this); $method = sprintf("_%s", $name); if (!$ref->hasMethod($method) || !$ref->getMethod($method)->isPublic()) { throw new Joy_Exception_NotFound_Method("Action Not Found ({$method})"); } // FIXME: ReflectionMethod class not found setAccesible method in PHP 5.2.10 version. $ref->getMethod($method)->setAccessible(TRUE); //->invokeArgs($this, $arguments); $view = $ref->getMethod($method)->invokeArgs($this, $arguments); // $view = call_user_method_array($method, $this, $arguments); if ($view == null) { $view = new Joy_View_Empty(); } // has layout if (!is_null($layout = $this->_canvas->getLayout())) { $layout = new Joy_View_Layout(array("file" => $layout)); $layout->setPlaceHolder($view); return $layout; } return $view; }
/** * {@inheritDoc} * * Build type from introspection of that class * * @api */ public function loadType($className, RdfMapperInterface $mapper, RdfTypeFactory $typeFactory) { if (!class_exists($className)) { throw new TypeNotFoundException('Class ' . $className . ' not found'); } $typenode = $this->createType($mapper, array()); /** @var $type TypeInterface */ $type = $typenode->getRdfElement(); $type->setVocabulary('lucky', 'http://localhost/lucky'); $typeof = strtr($className, '\\', '_'); $type->setRdfType('typeof', "lucky:{$typeof}"); $class = new \ReflectionClass($className); $methods = $class->getMethods(\ReflectionMethod::IS_PUBLIC); foreach ($methods as $method) { if (!strncmp($method->getShortName(), 'set', 3) && strlen($method->getShortName()) > 3) { $candidate = substr($method->getShortName(), 3); if ($class->hasMethod('get' . $candidate) && $class->getMethod('set' . $candidate)->getNumberOfParameters() == 1 && $class->getMethod('get' . $candidate)->getNumberOfParameters() == 0) { // TODO: introspect if method is using array value => collection instead of property $this->addProperty($typeFactory, $type, lcfirst($candidate)); } } } $fields = $class->getProperties(\ReflectionProperty::IS_PUBLIC); foreach ($fields as $field) { if (isset($type->{$field->getName()})) { // there was a getter and setter method for this continue; } $this->addProperty($typeFactory, $type, $field->getName()); } $this->classNames[$className] = $className; return $typenode; }
public function testGenerator() { /** @var OpsWay\Test2\Solid\I $generator */ $generator = OpsWay\Test2\Solid\Factory::create('d'); $generator->generate(); $this->assertFileExists($file = __DIR__ . '/../../test/D/IReader.php'); include $file; $this->assertTrue(interface_exists('IReader'), 'interface IReader not exists'); $this->assertFileExists($file = __DIR__ . '/../../test/D/CsvReader.php'); include $file; $this->assertTrue(class_exists('CsvReader'), 'class CsvReader not exists'); $this->assertTrue(method_exists('CsvReader', 'read'), 'Method read not exists in CsvReader'); $this->assertFileExists($file = __DIR__ . '/../../test/D/App.php'); include $file; $this->assertTrue(class_exists('App'), 'class App not exists'); $this->assertContains('private $reader', file_get_contents($file)); $this->assertFileExists($file = __DIR__ . '/../../test/D/run.php'); $this->assertContains('$app = new App();', file_get_contents($file)); $this->assertContains('print_r($app->parse());', file_get_contents($file)); $app = new ReflectionClass('App'); $this->assertGreaterThan(0, count($app->getMethods()), 'Too less methods in ' . $app->getName()); $construct = $app->getMethod('__construct'); $this->assertNotFalse($construct->getName()); $construct = $app->getMethod('parse'); $this->assertNotFalse($construct->getName()); $this->assertEquals(0, count($construct->getParameters()), 'Too less arguments in ' . $construct->getName()); $this->assertContains('$reader = new CsvReader();', file_get_contents($app->getFileName())); $this->assertContains('return $reader->read();', file_get_contents($app->getFileName())); $this->checkRead(new App()); }
/** * Tests AbstractStartServiceCommand. */ public function testAbstractStartServiceCommand() { /** @var OutputInterface|\PHPUnit_Framework_MockObject_MockObject $output */ $output = $this->getMockForAbstractClass('Symfony\\Component\\Console\\Output\\OutputInterface'); /** @var InputInterface|\PHPUnit_Framework_MockObject_MockObject $input */ $input = $this->getMockForAbstractClass('Symfony\\Component\\Console\\Input\\InputInterface'); $input->expects($this->once())->method('getArgument')->with('target')->willReturn('target'); $factory = $this->getMockBuilder('ONGR\\ConnectionsBundle\\Pipeline\\PipelineFactory')->setMethods(['setProgressBar'])->getMock(); $factory->method('setProgressBar')->will($this->returnValue(null)); /** @var PipelineStarter|\PHPUnit_Framework_MockObject_MockObject $PipelineStarter */ $pipelineStarter = $this->getMock('ONGR\\ConnectionsBundle\\Pipeline\\PipelineStarter'); $pipelineStarter->setPipelineFactory($factory); $pipelineStarter->method('getPipelineFactory')->will($this->returnValue($factory)); $pipelineStarter->expects($this->once())->method('startPipeline')->with('prefix', 'target'); /** @var ContainerInterface|\PHPUnit_Framework_MockObject_MockObject $container */ $container = $this->getMockForAbstractClass('Symfony\\Component\\DependencyInjection\\ContainerInterface'); $container->expects($this->any())->method('get')->with('PipelineStarterService')->willReturn($pipelineStarter); /** @var AbstractStartServiceCommand|\PHPUnit_Framework_MockObject_MockObject $command */ $command = $this->getMockBuilder('ONGR\\ConnectionsBundle\\Command\\AbstractStartServiceCommand')->setConstructorArgs(['name', 'description'])->setMethods(['addArgument', 'getContainer'])->getMock(); $command->expects($this->once())->method('addArgument')->with('target', InputArgument::OPTIONAL, $this->anything()); $command->expects($this->once())->method('getContainer')->willReturn($container); $reflection = new \ReflectionClass($command); $method = $reflection->getMethod('configure'); $method->setAccessible(true); $method->invoke($command); $method = $reflection->getMethod('start'); $method->setAccessible(true); $method->invoke($command, $input, $output, 'PipelineStarterService', 'prefix'); $this->assertEquals('description', $command->getDescription()); }
public function start() { //var_dump("APP start"); $actionParametersClassName = ''; $actionParametersClass = ''; $this->initController(); $reflectionController = new \ReflectionClass($this->controller); try { $action = $reflectionController->getMethod($this->actionName); } catch (\ReflectionException $e) { $this->actionName = self::DEFAULT_ACTION_NAME; $action = $reflectionController->getMethod($this->actionName); } if ($action->getParameters() != null) { $actionParametersClass = $action->getParameters()[0]->getClass(); $actionParametersClassName = $actionParametersClass->getName(); } if (preg_match('/\\w+BindingModel/', $actionParametersClassName)) { $bindModelInstance = new $actionParametersClassName(); $this->requestBindingModelInstance = $bindModelInstance; $bindModelProperties = $actionParametersClass->getProperties(); foreach ($bindModelProperties as $prop) { if (!isset($_POST[$prop->getName()])) { throw new \Exception("Parameters Do not respond to the Binding Model."); } $setterName = 'set' . $prop->getName(); $bindModelInstance->{$setterName}($_POST[$prop->getName()]); } $this->callControllerAction($this->requestBindingModelInstance); } else { $this->callControllerAction($this->requestParams); } }
/** * 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; }
public function testGetSingle() { $singletags = ['br', 'clear', 'col', 'hr', 'xkcd']; $method = $this->reflectionClass->getMethod('getSingle'); $this->parser = $this->reflectionClass->newInstance(); $this->assertEquals($singletags, $method->invoke($this->parser)); }
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 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 function addFilter($tag, $method, $priority = 1, $num_params = null) { if ($num_params === null) { $num_params = $this->reflection->getMethod($method)->getNumberOfParameters(); } add_filter($tag, [$this->object, $method], $priority, $num_params); }
public function route() { if (!class_exists($this->getController())) { $this->_controller = 'ErrorController'; $this->_action = 'viewAction'; } $rc = new ReflectionClass($this->getController()); if (!$rc->hasMethod($this->getAction())) { $this->_controller = 'ErrorController'; $this->_action = 'viewAction'; $rc = new ReflectionClass($this->getController()); } if ($rc->implementsInterface('IController')) { $controller = $rc->newInstance(); $method = $rc->getMethod($this->getAction()); try { $method->invoke($controller); } catch (AFHttpException $exc) { $this->_catch = $exc->getMessage(); $method = $rc->getMethod('catchAction'); $method->invoke($controller); } } else { echo 'No IController'; die; //??--- } }
/** * 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 scan() { $reflector = new ReflectionClass($this->parser); // Prime parser. Do things not appropriate to do in constructor. Most OS classes // don't have this. if ($reflector->hasMethod('init') && ($method = $reflector->getMethod('init'))) { $method->invoke($this->parser); } // Array fields, tied to method names and default values... $fields = array('OS' => array('show' => !empty($this->settings['show']['os']), 'default' => '', 'method' => 'getOS'), 'Kernel' => array('show' => !empty($this->settings['show']['kernel']), 'default' => '', 'method' => 'getKernel'), 'AccessedIP' => array('show' => !isset($this->settings['show']['ip']) || !empty($this->settings['show']['ip']), 'default' => '', 'method' => 'getAccessedIP'), 'Distro' => array('show' => !empty($this->settings['show']['distro']), 'default' => '', 'method' => 'getDistro'), 'RAM' => array('show' => !empty($this->settings['show']['ram']), 'default' => array(), 'method' => 'getRam'), 'HD' => array('show' => !empty($this->settings['show']['hd']), 'default' => array(), 'method' => 'getHD'), 'Mounts' => array('show' => !empty($this->settings['show']['mounts']), 'default' => array(), 'method' => 'getMounts'), 'Load' => array('show' => !empty($this->settings['show']['load']), 'default' => array(), 'method' => 'getLoad'), 'HostName' => array('show' => !empty($this->settings['show']['hostname']), 'default' => '', 'method' => 'getHostName'), 'UpTime' => array('show' => !empty($this->settings['show']['uptime']), 'default' => '', 'method' => 'getUpTime'), 'CPU' => array('show' => !empty($this->settings['show']['cpu']), 'default' => array(), 'method' => 'getCPU'), 'Model' => array('show' => !empty($this->settings['show']['model']), 'default' => array(), 'method' => 'getModel'), 'CPUArchitecture' => array('show' => !empty($this->settings['show']['cpu']), 'default' => '', 'method' => 'getCPUArchitecture'), 'Network Devices' => array('show' => !empty($this->settings['show']['network']), 'default' => array(), 'method' => 'getNet'), 'Devices' => array('show' => !empty($this->settings['show']['devices']), 'default' => array(), 'method' => 'getDevs'), 'Temps' => array('show' => !empty($this->settings['show']['temps']), 'default' => array(), 'method' => 'getTemps'), 'Battery' => array('show' => !empty($this->settings['show']['battery']), 'default' => array(), 'method' => 'getBattery'), 'Raid' => array('show' => !empty($this->settings['show']['raid']), 'default' => array(), 'method' => 'getRAID'), 'Wifi' => array('show' => !empty($this->settings['show']['wifi']), 'default' => array(), 'method' => 'getWifi'), 'SoundCards' => array('show' => !empty($this->settings['show']['sound']), 'default' => array(), 'method' => 'getSoundCards'), 'processStats' => array('show' => !empty($this->settings['show']['process_stats']), 'default' => array(), 'method' => 'getProcessStats'), 'services' => array('show' => !empty($this->settings['show']['services']), 'default' => array(), 'method' => 'getServices'), 'numLoggedIn' => array('show' => !empty($this->settings['show']['numLoggedIn']), 'default' => false, 'method' => 'getnumLoggedIn'), 'virtualization' => array('show' => !empty($this->settings['show']['virtualization']), 'default' => array(), 'method' => 'getVirtualization'), 'cpuUsage' => array('show' => !empty($this->settings['cpu_usage']), 'default' => false, 'method' => 'getCPUUsage'), 'phpVersion' => array('show' => !empty($this->settings['show']['phpversion']), 'default' => false, 'method' => 'getPhpVersion'), 'webService' => array('show' => !empty($this->settings['show']['webservice']), 'default' => false, 'method' => 'getWebService'), 'contains' => array('show' => true, 'default' => array(), 'method' => 'getContains')); foreach ($fields as $key => $data) { if (!$data['show']) { $this->info[$key] = $data['default']; continue; } try { $method = $reflector->getMethod($data['method']); $this->info[$key] = $method->invoke($this->parser); } catch (ReflectionException $e) { $this->info[$key] = $data['default']; } } // Add a timestamp $this->info['timestamp'] = date('c'); // Run extra extensions $this->runExtensions(); }
function process($path, $class = '') { if (empty($class)) { $class = str_replace('.php', '', basename($path)); } echo "Processing {$class} @ {$path}\n"; if (!file_exists($path)) { echo "Error: Path {$path} not found\n"; return; } require $path; if (!class_exists($class)) { echo "Error: Class {$class} does not exist in {$path}\n"; return; } $foo = new $class(); $getTpl = ' public function get%s() { return $this->%s; } '; $setTpl = ' public function set%s($value) { $this->%s = $value; } '; $newcode = ''; $reflect = new ReflectionClass($foo); $props = $reflect->getProperties(ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED); $methods = $reflect->getMethods(); foreach ($props as $prop) { $name = $prop->getName(); $upName = ucfirst($name); $method = 'get' . $upName; try { $reflect->getMethod($method); } catch (ReflectionException $ex) { echo " Missing {$method}\n"; $newcode .= sprintf($getTpl, $upName, $name); } $method = 'set' . $upName; try { $reflect->getMethod($method); } catch (ReflectionException $ex) { echo " Missing {$method}\n"; $newcode .= sprintf($setTpl, $upName, $name) . "\n"; } } if (empty($newcode)) { echo " No new code to add to {$class}\n"; return; } $code = file_get_contents($path); $pos = strrpos($code, '}'); $code = substr($code, 0, $pos) . "/* Added automatically " . date("Y-m-d") . " */\n\n" . $newcode . "\n\n}\n"; file_put_contents($path, $code); }
/** * @covers ::formatPlural */ public function testFormatPlural() { $method = $this->reflection->getMethod('formatPlural'); $method->setAccessible(TRUE); $result = $method->invoke($this->translation, 2, 'apple', 'apples'); $this->assertInstanceOf(PluralTranslatableMarkup::class, $result); $this->assertEquals('apples', $result); }
public function testFormatToDocLine() { $method = $this->reflectionClass->getMethod('formatToDocLine'); $method->setAccessible(true); $input = 'Some text '; $actual = $method->invoke($this->inst, $input); $this->assertEquals(' * Some text', $actual); }
/** * 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); } }
/** * Get the interactor name * * @return mixed * * @throws Exception\NonInteractorException */ public function getInteractorName() { if (!$this->isInteractor()) { throw new NonInteractorException($this->file->getFilename()); } $method = $this->reflection->getMethod(self::NAME_GETTER_METHOD); return $method->invoke($this->reflection->newInstanceWithoutConstructor(), self::NAME_GETTER_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; }
/** * @param string $methodName * @param array $methodParameters * @return mixed $methodReturn */ public function invokeMethod($methodName, array $methodParameters = []) { if (is_null($this->objectReflectionClass)) { $this->objectReflectionClass = new \ReflectionClass($this->objectToTest); } $method = $this->objectReflectionClass->getMethod($methodName); $method->setAccessible(true); return $method->invokeArgs($this->objectToTest, $methodParameters); }
/** * @covers: RI\FileManagerBundle\Model\UploadedFileParametersModel::normalizeSize */ public function testNormalizeSize() { $data = array(1150 => '1.12 ' . UploadedFileParametersModel::KB_UNIT, 2423231 => '2.31 ' . UploadedFileParametersModel::MB_UNIT, 2 => '2 ' . UploadedFileParametersModel::B_UNIT); $method = $this->uploadedFileParametersModelReflection->getMethod('normalizeSize'); $method->setAccessible(true); foreach ($data as $input => $expected) { $this->assertEquals($expected, $method->invokeArgs($this->uploadedFileParametersModel, array($input))); } }
/** * @test */ public function containsInvokeMethod() { try { $method = static::$reflection->getMethod('__invoke'); } catch (\Exception $e) { static::fail('Exception happened'); } static::assertEquals('__invoke', $method->name); }
/** * @test */ public function containsFilterMethod() { try { $method = static::$reflection->getMethod('validateProperties'); } catch (\Exception $e) { static::fail('Exception happened'); } static::assertEquals('validateProperties', $method->name); }