Example #1
0
 /**
  * Run the application
  */
 public function run()
 {
     // Determine the client-side path to root
     if (!empty($_SERVER['REQUEST_URI'])) {
         $this->rootPath = preg_replace('/(index\\.php)?(\\?.*)?$/', '', $_SERVER['REQUEST_URI']);
         if (!empty($_GET['q'])) {
             $this->rootPath = preg_replace('/' . preg_quote($_GET['q'], '/') . '$/', '', $this->rootPath);
         }
     }
     // Extract controller name, view name, action name and arguments from URL
     $controllerName = 'Index';
     if (!empty($_GET['q'])) {
         $this->args = explode('/', $_GET['q']);
         if ($this->args) {
             $controllerName = str_replace(' ', '/', ucwords(str_replace('_', ' ', str_replace('-', '', array_shift($this->args)))));
         }
         if ($action = $this->args ? array_shift($this->args) : '') {
             $this->action = str_replace('-', '', $action);
         }
     }
     if (!is_file('Swiftlet/Controllers/' . $controllerName . '.php')) {
         $controllerName = 'Error404';
     }
     $this->view = new View($this, strtolower($controllerName));
     // Instantiate the controller
     $controllerName = 'Swiftlet\\Controllers\\' . basename($controllerName);
     $this->controller = new $controllerName($this, $this->view);
     // Load plugins
     if ($handle = opendir('Swiftlet/Plugins')) {
         while (($file = readdir($handle)) !== FALSE) {
             if (is_file('Swiftlet/Plugins/' . $file) && preg_match('/^(.+)\\.php$/', $file, $match)) {
                 $pluginName = 'Swiftlet\\Plugins\\' . $match[1];
                 $this->plugins[$pluginName] = array();
                 foreach (get_class_methods($pluginName) as $methodName) {
                     $method = new \ReflectionMethod($pluginName, $methodName);
                     if ($method->isPublic() && !$method->isFinal() && !$method->isConstructor()) {
                         $this->plugins[$pluginName][] = $methodName;
                     }
                 }
             }
         }
         ksort($this->plugins);
         closedir($handle);
     }
     // Call the controller action
     $this->registerHook('actionBefore');
     if (method_exists($this->controller, $this->action)) {
         $method = new \ReflectionMethod($this->controller, $this->action);
         if ($method->isPublic() && !$method->isFinal() && !$method->isConstructor()) {
             $this->controller->{$this->action}();
         } else {
             $this->controller->notImplemented();
         }
     } else {
         $this->controller->notImplemented();
     }
     $this->registerHook('actionAfter');
     return array($this->view, $this->controller);
 }
Example #2
0
 /**
  * Returns whether this method is a constructor
  *
  * @return boolean TRUE if this method is a constructor
  */
 public function isConstructor()
 {
     if ($this->reflectionSource instanceof ReflectionMethod) {
         return $this->reflectionSource->isConstructor();
     } else {
         return parent::isConstructor();
     }
 }
Example #3
0
 /**
  * Determines if the method is suitable to be used by the processor.
  * (see \Magento\Framework\Reflection\MethodsMap::isSuitableMethod)
  *
  * @param \ReflectionMethod $method
  * @return bool
  */
 public function _isSuitableMethod(\ReflectionMethod $method)
 {
     /* '&&' usage is shorter then '||', if first part is 'false' then all equity is false */
     $isSuitableMethodType = !$method->isStatic() && !$method->isFinal() && !$method->isConstructor() && !$method->isDestructor();
     $isExcludedMagicMethod = strpos($method->getName(), '__') === 0;
     $result = $isSuitableMethodType && !$isExcludedMagicMethod;
     return $result;
 }
 private function _actionExists($action)
 {
     try {
         $method = new ReflectionMethod(get_class($this), $action);
         return $method->isPublic() && !$method->isConstructor();
     } catch (Exception $e) {
         return false;
     }
 }
Example #5
0
 /**
  * @inheritdoc
  */
 public function condition(\ReflectionMethod $method)
 {
     if ($method->isPublic() && !($method->isAbstract() || $method->isConstructor() || $method->isDestructor())) {
         if ($this->isTest || strlen($method->name) > 4 && substr($method->name, 0, 4) === 'test') {
             return true;
         }
     }
     return false;
 }
Example #6
0
 /**
  * Load and run a test.
  * 
  * @param string $name Name of test to run. This test should be located in {package}/tests
  * folder.
  * 
  * @return NULL
  */
 public function run($name)
 {
     // Ready the report.
     $report = new View_Component('test-result');
     $report->outcome = 'pass';
     $report->passes = 0;
     $report->fails = 0;
     $report->test_count = 0;
     $results = array();
     // Load test.
     $test = ucfirst(strtolower($name)) . '_Test';
     $report->test = $test;
     $reflector = new ReflectionClass($test);
     // Is it enabled?
     $constants = $reflector->getConstants();
     if ($constants['ENABLED'] === TRUE) {
         $report->status = 'Enabled';
         // Get the public methods, they are our tests.
         $public_methods = $reflector->getMethods(ReflectionMethod::IS_PUBLIC);
         $runnable = array();
         foreach ($public_methods as $public_method) {
             $method = new ReflectionMethod($test, $public_method->name);
             // Constructor and Destructor should be used for setup/teardown only.
             if (!$method->isConstructor() && !$method->isDestructor()) {
                 $runnable[] = $method;
             }
         }
         // Run each test.
         $report->test_count = count($runnable);
         foreach ($runnable as $run) {
             $result = new stdClass();
             $result->test = $run->name;
             // Expectations will trigger Exceptions on failure.
             try {
                 $run->invoke(new $test());
                 $result->outcome = 'pass';
                 $report->passes++;
             } catch (Exception $e) {
                 $report->fails++;
                 $report->outcome = 'fail';
                 $result->outcome = 'fail';
                 $result->error = $e->getMessage();
             }
             array_push($results, $result);
         }
     } else {
         $report->status = 'Disabled';
     }
     $report->results = $results;
     $report->display_content();
 }
 /**
  * Realiza el dispatch de una ruta
  *
  * @return Object
  */
 public static function execute($route)
 {
     extract($route, EXTR_OVERWRITE);
     if (!(include_once APP_PATH . "controllers/{$controller_path}" . '_controller.php')) {
         throw new KumbiaException(NULL, 'no_controller');
     }
     //Asigna el controlador activo
     $app_controller = Util::camelcase($controller) . 'Controller';
     $cont = self::$_controller = new $app_controller($module, $controller, $action, $parameters);
     View::select($action);
     View::setPath($controller_path);
     // Se ejecutan los filtros before
     if ($cont->k_callback('initialize') === FALSE) {
         return $cont;
     }
     if ($cont->k_callback('before_filter') === FALSE) {
         return $cont;
     }
     //Se ejecuta el metodo con el nombre de la accion
     //en la clase de acuerdo al convenio
     if (!method_exists($cont, $action)) {
         throw new KumbiaException(NULL, 'no_action');
     }
     //Obteniendo el metodo
     $reflectionMethod = new ReflectionMethod($cont, $action);
     //k_callback y __constructor metodo reservado
     if ($reflectionMethod->name == 'k_callback' || $reflectionMethod->isConstructor()) {
         throw new KumbiaException('Esta intentando ejecutar un método reservado de KumbiaPHP');
     }
     //se verifica que el metodo sea public
     if (!$reflectionMethod->isPublic()) {
         throw new KumbiaException(NULL, 'no_action');
     }
     //se verifica que los parametros que recibe
     //la action sea la cantidad correcta
     $num_params = count($parameters);
     if ($cont->limit_params && ($num_params < $reflectionMethod->getNumberOfRequiredParameters() || $num_params > $reflectionMethod->getNumberOfParameters())) {
         throw new KumbiaException("Número de parámetros erroneo para ejecutar la acción \"{$action}\" en el controlador \"{$controller}\"");
     }
     $reflectionMethod->invokeArgs($cont, $parameters);
     //Corre los filtros after
     $cont->k_callback('after_filter');
     $cont->k_callback('finalize');
     //Si esta routed volver a ejecutar
     if (Router::getRouted()) {
         Router::setRouted(FALSE);
         return Dispatcher::execute(Router::get());
         // Vuelve a ejecutar el dispatcher
     }
     return $cont;
 }
Example #8
0
 public function JResponse() {
     $result = null;
     if ($this->doAuthenticate()) {
         $mn = filter_input(INPUT_GET,self::$methodName,FILTER_SANITIZE_STRING);
         if (($mn!=null) && ($mn!=false)) {                
             if (method_exists($this, $mn)) {
                 $rfm = new ReflectionMethod($this, $mn);
                 if (( $rfm->isPublic() ) && (!$rfm->isConstructor() ) && (!$rfm->isDestructor() )) {
                     $result = call_user_func(array($this, $mn));
                     $this->doResponse($result);
                 } else
                     $this->doError("Method is not callable");
             } else
                 $this->doError("Method dose not exist");
         } else
             $this->doError("Method must be specified");
     } else
         $this->doError("Unauthorized");
     
 }
Example #9
0
 /**
  * This method prevents catchable fatal errors when calling the API with missing arguments
  * @param string $method
  * @param array $arguments
  */
 protected function validateCall($controller, $method, $arguments)
 {
     if (get_class($controller) == 'vB_Api_Null') {
         /* No such Class in the core controllers
            but it may be defined in an extension */
         return 0;
     }
     if (method_exists($controller, $method)) {
         $reflection = new ReflectionMethod($controller, $method);
     } else {
         /* No such Method in the core controller
            but it may be defined in an extension */
         return 0;
     }
     if ($reflection->isStatic()) {
         return 2;
     }
     if ($reflection->isConstructor()) {
         return 3;
     }
     if ($reflection->isDestructor()) {
         return 4;
     }
     $index = 0;
     foreach ($reflection->getParameters() as $param) {
         if (!isset($arguments[$index])) {
             if (!$param->allowsNull() and !$param->isDefaultValueAvailable()) {
                 // cannot omit parameter
                 throw new vB_Exception_Api('invalid_data');
             }
         } else {
             if ($param->isArray() and !is_array($arguments[$index])) {
                 // array type was expected
                 throw new vB_Exception_Api('invalid_data');
             }
         }
         $index++;
     }
     return 1;
 }
Example #10
0
    public function response() {
        parent::response();
        $this->setError("", 0);

        $mn = $this->method;
        if (method_exists($this, $mn)) {
            $rfm = new ReflectionMethod($this, $mn);
            if (( $rfm->isPublic() ) && (!$rfm->isConstructor() ) && (!$rfm->isDestructor() ) 
                    && ( $mn != "response" ) && ( $mn != "isError" ) && ($mn != "setOperation")
                    && ( $mn != "getError" ) && ( $mn != "getErrorCode" )
                ) {
                $response = call_user_func(array($this, $mn));
                return $response;
            } else {
                $this->setError("Method Access Problem", 2002);
                return false;
            }
        } else {
            $this->setError("Method not found", 2001);            
            return false;
        }
    }
Example #11
0
function reflectMethod($class, $method)
{
    $methodInfo = new ReflectionMethod($class, $method);
    echo "**********************************\n";
    echo "Reflecting on method {$class}::{$method}()\n\n";
    echo "\nisFinal():\n";
    var_dump($methodInfo->isFinal());
    echo "\nisAbstract():\n";
    var_dump($methodInfo->isAbstract());
    echo "\nisPublic():\n";
    var_dump($methodInfo->isPublic());
    echo "\nisPrivate():\n";
    var_dump($methodInfo->isPrivate());
    echo "\nisProtected():\n";
    var_dump($methodInfo->isProtected());
    echo "\nisStatic():\n";
    var_dump($methodInfo->isStatic());
    echo "\nisConstructor():\n";
    var_dump($methodInfo->isConstructor());
    echo "\nisDestructor():\n";
    var_dump($methodInfo->isDestructor());
    echo "\n**********************************\n";
}
Example #12
0
function methodData(ReflectionMethod $method)
{
    $details = "";
    $name = $method->getName();
    if ($method->isUserDefined()) {
        $details .= "{$name} is user defined\n";
    }
    if ($method->isInternal()) {
        $details .= "{$name} is built-in\n";
    }
    if ($method->isAbstract()) {
        $details .= "{$name} is abstract\n";
    }
    if ($method->isPublic()) {
        $details .= "{$name} is public\n";
    }
    if ($method->isProtected()) {
        $details .= "{$name} is protected\n";
    }
    if ($method->isPrivate()) {
        $details .= "{$name} is private\n";
    }
    if ($method->isStatic()) {
        $details .= "{$name} is static\n";
    }
    if ($method->isFinal()) {
        $details .= "{$name} is final\n";
    }
    if ($method->isConstructor()) {
        $details .= "{$name} is the constructor\n";
    }
    if ($method->returnsReference()) {
        $details .= "{$name} returns a reference (as opposed to a value)\n";
    }
    return $details;
}
Example #13
0
 /**
  * Determines if the method is suitable to be used by the processor.
  *
  * @param \ReflectionMethod $method
  * @return bool
  */
 private function isSuitableMethod($method)
 {
     $isSuitableMethodType = !($method->isConstructor() || $method->isFinal() || $method->isStatic() || $method->isDestructor());
     $isExcludedMagicMethod = strpos($method->getName(), '__') === 0;
     return $isSuitableMethodType && !$isExcludedMagicMethod;
 }
Example #14
0
 /**
  * Given a user-defined PHP class or php object, map its methods onto a list of
  * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc server
  * object and called from remote clients (as well as their corresponding signature info).
  *
  * @param string|object $className the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class
  * @param array $extraOptions see the docs for wrapPhpMethod for basic options, plus
  *                            - string method_type    'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on whether $className is a class name or object instance
  *                            - string method_filter  a regexp used to filter methods to wrap based on their names
  *                            - string prefix         used for the names of the xmlrpc methods created
  *
  * @return array|false false on failure
  */
 public function wrapPhpClass($className, $extraOptions = array())
 {
     $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : '';
     $methodType = isset($extraOptions['method_type']) ? $extraOptions['method_type'] : 'auto';
     $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : '';
     $results = array();
     $mList = get_class_methods($className);
     foreach ($mList as $mName) {
         if ($methodFilter == '' || preg_match($methodFilter, $mName)) {
             $func = new \ReflectionMethod($className, $mName);
             if (!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) {
                 if ($func->isStatic() && ($methodType == 'all' || $methodType == 'static' || $methodType == 'auto' && is_string($className)) || !$func->isStatic() && ($methodType == 'all' || $methodType == 'nonstatic' || $methodType == 'auto' && is_object($className))) {
                     $methodWrap = $this->wrapPhpFunction(array($className, $mName), '', $extraOptions);
                     if ($methodWrap) {
                         if (is_object($className)) {
                             $realClassName = get_class($className);
                         } else {
                             $realClassName = $className;
                         }
                         $results[$prefix . "{$realClassName}.{$mName}"] = $methodWrap;
                     }
                 }
             }
         }
     }
     return $results;
 }
Example #15
0
$class = ucfirst($RTR->class);
$method = $RTR->method;
if (empty($class) or !file_exists(APPPATH . 'controllers/' . $RTR->directory . $class . '.php')) {
    $e404 = TRUE;
} else {
    require_once APPPATH . 'controllers/' . $RTR->directory . $class . '.php';
    if (!class_exists($class, FALSE) or $method[0] === '_' or method_exists('CI_Controller', $method)) {
        $e404 = TRUE;
    } elseif (method_exists($class, '_remap')) {
        $params = array($method, array_slice($URI->rsegments, 2));
        $method = '_remap';
    } elseif (!method_exists($class, $method)) {
        $e404 = TRUE;
    } elseif (!is_callable(array($class, $method)) && strcasecmp($class, $method) === 0) {
        $reflection = new ReflectionMethod($class, $method);
        if (!$reflection->isPublic() or $reflection->isConstructor()) {
            $e404 = TRUE;
        }
    }
}
if ($e404) {
    if (!empty($RTR->routes['404_override'])) {
        if (sscanf($RTR->routes['404_override'], '%[^/]/%s', $error_class, $error_method) !== 2) {
            $error_method = 'index';
        }
        $error_class = ucfirst($error_class);
        if (!class_exists($error_class, FALSE)) {
            if (file_exists(APPPATH . 'controllers/' . $RTR->directory . $error_class . '.php')) {
                require_once APPPATH . 'controllers/' . $RTR->directory . $error_class . '.php';
                $e404 = !class_exists($error_class, FALSE);
            } elseif (!empty($RTR->directory) && file_exists(APPPATH . 'controllers/' . $error_class . '.php')) {
 /**
  * @param  ReflectionMethod $method
  *
  * @return boolean
  */
 protected function canMockMethod(ReflectionMethod $method)
 {
     if ($method->isConstructor() || $method->isFinal() || $method->isPrivate() || isset($this->blacklistedMethodNames[$method->getName()])) {
         return false;
     }
     return true;
 }
Example #17
0
 /**
  * Load listeners
  * @return App
  */
 public function loadListeners()
 {
     // Load listeners
     if ($handle = opendir($this->vendorPath . str_replace('\\', '/', $this->vendor . '/Listeners'))) {
         while (($file = readdir($handle)) !== false) {
             $listenerClass = $this->vendor . '\\Listeners\\' . preg_replace('/\\.php$/', '', $file);
             if (is_file($this->vendorPath . str_replace('\\', '/', $listenerClass) . '.php')) {
                 $this->listeners[$listenerClass] = array();
                 $reflection = new \ReflectionClass($listenerClass);
                 $parentClass = $reflection->getParentClass();
                 foreach (get_class_methods($listenerClass) as $methodName) {
                     $method = new \ReflectionMethod($listenerClass, $methodName);
                     if ($method->isPublic() && !$method->isFinal() && !$method->isConstructor() && !$parentClass->hasMethod($methodName)) {
                         $this->listeners[$listenerClass][] = $methodName;
                     }
                 }
             }
         }
         ksort($this->listeners);
         closedir($handle);
     }
     return $this;
 }
        echo "In " . __METHOD__ . "\n";
    }
    function __construct()
    {
        echo "In " . __METHOD__ . "\n";
    }
}
echo "\nOld-style constructor:\n";
$methodInfo = new ReflectionMethod("OldAndNewCtor::OldAndNewCtor");
var_dump($methodInfo->isConstructor());
echo "\nRedefined constructor:\n";
$methodInfo = new ReflectionMethod("OldAndNewCtor::__construct");
var_dump($methodInfo->isConstructor());
class NewAndOldCtor
{
    function __construct()
    {
        echo "In " . __METHOD__ . "\n";
    }
    function NewAndOldCtor()
    {
        echo "In " . __METHOD__ . "\n";
    }
}
echo "\nNew-style constructor:\n";
$methodInfo = new ReflectionMethod("NewAndOldCtor::__construct");
var_dump($methodInfo->isConstructor());
echo "\nRedefined old-style constructor:\n";
$methodInfo = new ReflectionMethod("NewAndOldCtor::NewAndOldCtor");
var_dump($methodInfo->isConstructor());
 /**
  * Realiza el dispatch de la ruta actual
  *
  * @return Controller
  */
 private static function _dispatch()
 {
     // Extrae las variables para manipularlas facilmente
     extract(self::$_vars, EXTR_OVERWRITE);
     if (!(include_once APP_PATH . "controllers/{$controller_path}" . '_controller.php')) {
         throw new KumbiaException(null, 'no_controller');
     }
     View::select($action);
     //TODO: mover al constructor del controller base las 2 lineas
     View::setPath($controller_path);
     //Asigna el controlador activo
     $app_controller = Util::camelcase($controller) . 'Controller';
     $cont = new $app_controller($module, $controller, $action, $parameters);
     // Se ejecutan los filtros initialize y before
     if ($cont->k_callback(true) === false) {
         return $cont;
     }
     //Obteniendo el metodo
     try {
         $reflectionMethod = new ReflectionMethod($cont, $cont->action_name);
     } catch (ReflectionException $e) {
         throw new KumbiaException(null, 'no_action');
         //TODO: enviar a un método del controller
     }
     //k_callback y __constructor metodo reservado
     if ($cont->action_name == 'k_callback' || $reflectionMethod->isConstructor()) {
         throw new KumbiaException('Esta intentando ejecutar un método reservado de KumbiaPHP');
     }
     //se verifica que los parametros que recibe
     //la action sea la cantidad correcta
     $num_params = count($cont->parameters);
     if ($cont->limit_params && ($num_params < $reflectionMethod->getNumberOfRequiredParameters() || $num_params > $reflectionMethod->getNumberOfParameters())) {
         throw new KumbiaException(NULL, 'num_params');
     }
     try {
         $reflectionMethod->invokeArgs($cont, $cont->parameters);
     } catch (ReflectionException $e) {
         throw new KumbiaException(null, 'no_action');
         //TODO: mejor no_public
     }
     //Corre los filtros after y finalize
     $cont->k_callback();
     //Si esta routed internamente volver a ejecutar
     if (self::$_routed) {
         self::$_routed = FALSE;
         return self::_dispatch();
         // Vuelve a ejecutar el dispatcher
     }
     return $cont;
 }
Example #20
0
<?php

class Root
{
    function Root()
    {
    }
}
class Base extends Root
{
    function __construct()
    {
    }
}
class Derived extends Base
{
}
$a = new ReflectionMethod('Root', 'Root');
$b = new ReflectionMethod('Base', 'Root');
$c = new ReflectionMethod('Base', '__construct');
$d = new ReflectionMethod('Derived', 'Root');
$e = new ReflectionMethod('Derived', '__construct');
var_dump($a->isConstructor());
var_dump($b->isConstructor());
var_dump($c->isConstructor());
var_dump($d->isConstructor());
var_dump($e->isConstructor());
?>
===DONE===
Example #21
0
 /**
  * Determine if the given method may be proxied.
  *
  * Since it is not possible to reflect a
  *  - constructor
  *  - final method
  *  - static method
  * those will cause this method to return false.
  * Also methods registered in the blacklist will cause this
  * method to return false.
  *
  * @param \ReflectionMethod $method Name of the method to be reflected.
  *
  * @return boolean True, if the given method may be reflected, else false.
  */
 protected static function canProxyMethod(\ReflectionMethod $method)
 {
     if ($method->isConstructor() || $method->isFinal() || $method->isStatic() || isset(self::$blacklistedMethodNames[$method->getName()])) {
         return false;
     } elseif ($method->isProtected()) {
         return true;
     }
     return false;
 }
/**
 * Given a user-defined PHP class or php object, map its methods onto a list of
 * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc_server
 * object and called from remote clients (as well as their corresponding signature info).
 *
 * @param mixed $classname the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class
 * @param array $extra_options see the docs for wrap_php_method for more options
 *        string method_type 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on wheter $classname is a class name or object instance
 * @return array or false on failure
 *
 * @todo get_class_methods will return both static and non-static methods.
 *       we have to differentiate the action, depending on wheter we recived a class name or object
 */
function wrap_php_class($classname, $extra_options = array())
{
    $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : '';
    $methodtype = isset($extra_options['method_type']) ? $extra_options['method_type'] : 'auto';
    if (version_compare(phpversion(), '5.0.3') == -1) {
        // up to php 5.0.3 some useful reflection methods were missing
        error_log('XML-RPC: cannot not wrap php functions unless running php version bigger than 5.0.3');
        return false;
    }
    $result = array();
    $mlist = get_class_methods($classname);
    foreach ($mlist as $mname) {
        if ($methodfilter == '' || preg_match($methodfilter, $mname)) {
            // echo $mlist."\n";
            $func = new ReflectionMethod($classname, $mname);
            if (!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) {
                if ($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || $methodtype == 'auto' && is_string($classname)) || !$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || $methodtype == 'auto' && is_object($classname))) {
                    $methodwrap = wrap_php_function(array($classname, $mname), '', $extra_options);
                    if ($methodwrap) {
                        $result[$methodwrap['function']] = $methodwrap['function'];
                    }
                }
            }
        }
    }
    return $result;
}
Example #23
0
 /**
  * Decides if the given method is a good one
  *
  * @param \ReflectionMethod $method Method to be called
  * @return bool
  */
 private static function isGoodMethod(\ReflectionMethod $method)
 {
     $is_good_method = $method->isPublic() && !$method->isConstructor() && !$method->isStatic();
     return $is_good_method;
 }
Example #24
0
<?php

trait Foo
{
    public function Foo()
    {
    }
}
class Bar
{
    use Foo;
    public function Bar()
    {
    }
}
$rfoofoo = new ReflectionMethod('Foo::Foo');
var_dump($rfoofoo->isConstructor());
$rbarfoo = new ReflectionMethod('Bar::Foo');
var_dump($rbarfoo->isConstructor());
$rbarbar = new ReflectionMethod('Bar::Bar');
var_dump($rbarbar->isConstructor());
<pre>
<?php 
class Counter
{
    private static $c = 0;
    public static final function increment()
    {
        return ++self::$c;
    }
}
// Создание экземпляра класса ReflectionMethod
$method = new ReflectionMethod('Counter', 'increment');
// exit;
// Вывод основной информации
printf("===> %s%s%s%s%s%s%s метод '%s' (который является %s)\n" . "     объявлен в %s\n" . "     строки с %d по %d\n" . "     имеет модификаторы %d[%s]\n", $method->isInternal() ? 'Встроенный' : 'Пользовательский', $method->isAbstract() ? ' абстрактный' : '', $method->isFinal() ? ' финальный' : '', $method->isPublic() ? ' public' : '', $method->isPrivate() ? ' private' : '', $method->isProtected() ? ' protected' : '', $method->isStatic() ? ' статический' : '', $method->getName(), $method->isConstructor() ? 'конструктором' : 'обычным методом', $method->getFileName(), $method->getStartLine(), $method->getEndline(), $method->getModifiers(), implode(' ', Reflection::getModifierNames($method->getModifiers())));
// Вывод статических переменных, если они есть
if ($statics = $method->getStaticVariables()) {
    printf("---> Статическая переменная: %s\n", var_export($statics, 1));
}
// Вызов метода
printf("---> Результат вызова: ");
$result = $method->invoke(3);
echo $result;
?>
</pre>
Example #26
0
 /**
  * Executes a specific Selenium System Tests in your machine
  *
  * @param string $seleniumPath   Optional path to selenium-standalone-server-x.jar
  * @param string $pathToTestFile Optional name of the test to be run
  * @param string $suite          Optional name of the suite containing the tests, Acceptance by default.
  *
  * @return mixed
  */
 public function runTest($pathToTestFile = null, $suite = 'acceptance')
 {
     $this->runSelenium();
     // Make sure to run the build command to generate AcceptanceTester
     $this->_exec($this->isWindows() ? 'vendor\\bin\\codecept.bat build' : 'php vendor/bin/codecept build');
     if (!$pathToTestFile) {
         $this->say('Available tests in the system:');
         $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('tests/' . $suite, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST);
         $tests = array();
         $iterator->rewind();
         $i = 1;
         while ($iterator->valid()) {
             if (strripos($iterator->getSubPathName(), 'cept.php') || strripos($iterator->getSubPathName(), 'cest.php')) {
                 $this->say('[' . $i . '] ' . $iterator->getSubPathName());
                 $tests[$i] = $iterator->getSubPathName();
                 $i++;
             }
             $iterator->next();
         }
         $this->say('');
         $testNumber = $this->ask('Type the number of the test  in the list that you want to run...');
         $test = $tests[$testNumber];
     }
     $pathToTestFile = 'tests/' . $suite . '/' . $test;
     //loading the class to display the methods in the class
     require 'tests/' . $suite . '/' . $test;
     //logic to fetch the class name from the file name
     $fileName = explode("/", $test);
     $className = explode(".", $fileName[1]);
     //if the selected file is cest only than we will give the option to execute individual methods, we don't need this in cept file
     $i = 1;
     if (strripos($className[0], 'cest')) {
         $class_methods = get_class_methods($className[0]);
         $this->say('[' . $i . '] ' . 'All');
         $methods[$i] = 'All';
         $i++;
         foreach ($class_methods as $method_name) {
             $reflect = new ReflectionMethod($className[0], $method_name);
             if (!$reflect->isConstructor()) {
                 if ($reflect->isPublic()) {
                     $this->say('[' . $i . '] ' . $method_name);
                     $methods[$i] = $method_name;
                     $i++;
                 }
             }
         }
         $this->say('');
         $methodNumber = $this->ask('Please choose the method in the test that you would want to run...');
         $method = $methods[$methodNumber];
     }
     if (isset($method) && $method != 'All') {
         $pathToTestFile = $pathToTestFile . ':' . $method;
     }
     $this->taskCodecept()->test($pathToTestFile)->arg('--steps')->arg('--debug')->run()->stopOnFail();
 }
Example #27
0
 /**
  * Whether method is intercepted
  *
  * @param \ReflectionMethod $method
  * @return bool
  */
 protected function isInterceptedMethod(\ReflectionMethod $method)
 {
     return !($method->isConstructor() || $method->isFinal() || $method->isStatic() || $method->isDestructor()) && !in_array($method->getName(), ['__sleep', '__wakeup', '__clone']);
 }
 /**
  * @param  ReflectionMethod $method
  * @return boolean
  */
 protected static function canMockMethod(ReflectionMethod $method)
 {
     if ($method->isConstructor() || $method->isFinal() || isset(self::$blacklistedMethodNames[$method->getName()])) {
         return FALSE;
     }
     return TRUE;
 }
 /**
  * Generate proxy method
  *
  * @param \ReflectionMethod $method
  *
  * @return string
  */
 private function generateProxyMethod(\ReflectionMethod $method)
 {
     if ($method->isConstructor()) {
         throw new \RuntimeException(sprintf('Can not generate proxy method for constructor in class "%s".', $method->getDeclaringClass()->getName()));
     }
     if ($method->isStatic()) {
         throw new \RuntimeException(sprintf('Can not generate proxy method for static method "%s" in class "%s".', $method->getName(), $method->getDeclaringClass()->getName()));
     }
     if ($method->isPrivate()) {
         throw new \RuntimeException(sprintf('Can not generate proxy for private method "%s" in class "%s".', $method->getName(), $method->getDeclaringClass()->getName()));
     }
     $proxyMethodParameters = [];
     $methodParameters = [];
     foreach ($method->getParameters() as $methodParameter) {
         $methodParameters[] = '$' . $methodParameter->getName();
         if ($methodParameter->getClass()) {
             $proxyMethodParameter = sprintf('\\%s %s', $methodParameter->getClass()->getName(), '$' . $methodParameter->getName());
         } else {
             $proxyMethodParameter = '$' . $methodParameter->getName();
         }
         if ($methodParameter->isOptional()) {
             $proxyMethodParameter .= ' = ' . var_export($methodParameter->getDefaultValue(), true);
         }
         $proxyMethodParameters[] = $proxyMethodParameter;
     }
     if ($method->isPublic()) {
         $availability = 'public';
     } elseif ($method->isProtected()) {
         $availability = 'protected';
     } else {
         throw new \RuntimeException(sprintf('Not support availability for method "%s" in class "%s".', $method->getName(), $method->getDeclaringClass()->getName()));
     }
     $docComment = $method->getDocComment();
     $docComment = $this->formatDocComment($docComment);
     $templateVariables = ['docComment' => $docComment, 'availability' => $availability, 'name' => $method->getName(), 'proxyMethodParameters' => implode(', ', $proxyMethodParameters), 'parameters' => implode(', ', $methodParameters), 'beginArguments' => null, 'rollbackArguments' => null, 'commitArguments' => null];
     $methodTemplate = $this->getTemplateForProxyMethod();
     $methodCode = $this->replaceVariables($methodTemplate, $templateVariables);
     $methodCode = $this->appendTabulationCharacter($methodCode, 1);
     return $methodCode;
 }
Example #30
0
 /**
  * @return bool
  */
 public function isConstructor()
 {
     $rc = $this->reflectionMethod->isConstructor();
     return $rc;
 }