/**
  * Exports the PHP code
  *
  * @return string
  */
 public function exportCode()
 {
     $modifiers = \Reflection::getModifierNames($this->_method->getModifiers());
     $params = array();
     // Export method's parameters
     foreach ($this->_method->getParameters() as $param) {
         $reflection_parameter = new ReflectionParameter($param);
         $params[] = $reflection_parameter->exportCode();
     }
     return sprintf('%s function %s(%s) {}', join(' ', $modifiers), $this->_method->getName(), join(', ', $params));
 }
Example #2
0
 public function writeMethod(\ReflectionMethod $method)
 {
     $args = [];
     foreach ($method->getParameters() as $parameter) {
         $arg = '';
         if ($parameter->isArray()) {
             $arg .= 'array ';
         } else {
             if ($parameter->getClass()) {
                 $arg .= '\\' . $parameter->getClass()->getName() . ' ';
             }
         }
         if ($parameter->isPassedByReference()) {
             $arg .= '&';
         }
         $arg .= '$' . $parameter->getName();
         try {
             $defaultValue = $parameter->getDefaultValue();
             $arg .= ' = ' . var_export($defaultValue, true);
         } catch (ReflectionException $e) {
             if ($parameter->isOptional()) {
                 $arg .= ' = null';
             }
         }
         $args[] = $arg;
     }
     $modifiers = array_diff(\Reflection::getModifierNames($method->getModifiers()), ['abstract']);
     $methodName = ($method->returnsReference() ? '&' : '') . $method->getName();
     $this->code[] = '  ' . implode(' ', $modifiers) . ' function ' . $methodName . '(' . implode(', ', $args) . ') {';
     $this->code[] = '    $result = $this->' . $this->propertyName . '->invoke($this, \'' . $method->getName() . '\', func_get_args());';
     $this->code[] = '    return $result;';
     $this->code[] = '  }';
 }
Example #3
0
 /**
  * Returns a bitfield of the access modifiers for this method
  *
  * @return integer Bitfield of the access modifiers for this method
  */
 public function getModifiers()
 {
     if ($this->reflectionSource instanceof ReflectionMethod) {
         return $this->reflectionSource->getModifiers();
     } else {
         return parent::getModifiers();
     }
 }
Example #4
0
 /**
  * @return Method[]
  */
 public static function methodListFromReflectionClassAndMethod(Context $context, CodeBase $code_base, \ReflectionClass $class, \ReflectionMethod $reflection_method) : array
 {
     $reflection_method = new \ReflectionMethod($class->getName(), $reflection_method->name);
     $method = new Method($context, $reflection_method->name, new UnionType(), $reflection_method->getModifiers());
     $method->setNumberOfRequiredParameters($reflection_method->getNumberOfRequiredParameters());
     $method->setNumberOfOptionalParameters($reflection_method->getNumberOfParameters() - $reflection_method->getNumberOfRequiredParameters());
     $method->setFQSEN(FullyQualifiedMethodName::fromStringInContext($method->getName(), $context));
     return self::functionListFromFunction($method, $code_base);
 }
Example #5
0
 /**
  * @param ReflectionMethod[] $methods
  */
 private function checkMethodsInNewClasses($methods)
 {
     foreach ($methods as $method) {
         list($expectedMethod, $class) = $this->explodeCamel($method->getName());
         $this->assertTrue(method_exists($class, $expectedMethod), 'Method ' . $expectedMethod . ' is not found in class ' . $class);
         $newMethod = new ReflectionMethod($class, $expectedMethod);
         $this->assertEquals($method->getModifiers(), $newMethod->getModifiers(), 'Incorrect modifier for ' . $class . '::' . $expectedMethod);
         $this->assertEquals(substr_count(file_get_contents($method->getFileName()), $method->getName()), substr_count(file_get_contents($newMethod->getFileName()), $newMethod->getName()), 'Incorrect usage for ' . $class . '::' . $expectedMethod);
     }
 }
 /**
  * {@inheritdoc}
  * @throws MethodDefinitionAlreadyExistsException
  * @throws MethodDefinitionNotFoundException
  */
 public function analyze(DefinitionAnalyzer $analyzer, ClassDefinition $classDefinition, \ReflectionMethod $reflectionMethod)
 {
     $methodName = $reflectionMethod->getName();
     // Constructor definition is required
     if ($methodName === '__construct' && !$classDefinition->hasMethod('__construct')) {
         $classDefinition->defineConstructor()->end();
     }
     // Set method metadata
     if ($classDefinition->hasMethod($methodName)) {
         $classDefinition->getMethod($methodName)->setModifiers($reflectionMethod->getModifiers())->setIsPublic($reflectionMethod->isPublic());
     }
 }
Example #7
0
 /**
  * @param ReflectionMethod $method
  * @return int
  */
 private function getMethodModifier($method)
 {
     switch ($method->getModifiers()) {
         case '134283520':
             return self::PUBLIC_MODIFIER;
         case '134283776':
             return self::PROTECTED_MODIFIER;
         case '134284288':
             return self::PRIVATE_MODIFIER;
         default:
             return self::PUBLIC_MODIFIER;
     }
 }
 public function __construct($class, $method)
 {
     $method = new ReflectionMethod($class, $method);
     $this->name = $method->name;
     $class = $parent = $method->getDeclaringClass();
     if ($modifiers = $method->getModifiers()) {
         $this->modifiers = '<small>' . implode(' ', Reflection::getModifierNames($modifiers)) . '</small> ';
     }
     $comment = '';
     do {
         if ($parent->hasMethod($this->name)) {
             $comment = $parent->getMethod($this->name)->getDocComment();
             // Found a description for this method
             break;
         }
     } while ($parent = $parent->getParentClass());
     list($this->description, $tags) = Kodoc::parse($comment);
     if ($file = $class->getFileName()) {
         $this->source = Kodoc::source($file, $method->getStartLine(), $method->getEndLine());
     }
     if (isset($tags['param'])) {
         $params = array();
         foreach ($method->getParameters() as $i => $param) {
             $param = new Kodoc_Method_Param(array($method->class, $method->name), $i);
             if (isset($tags['param'][$i])) {
                 if (preg_match('/^(\\S*)\\s*(\\$\\w+)?(?:\\s*(.+?))?$/', $tags['param'][$i], $matches)) {
                     $param->type = $matches[1];
                     $param->description = arr::get($matches, 3);
                 }
             }
             $params[] = $param;
         }
         $this->params = $params;
         unset($tags['param']);
     }
     if (isset($tags['return'])) {
         foreach ($tags['return'] as $return) {
             if (preg_match('/^(\\S*)(?:\\s*(.+?))?$/', $return, $matches)) {
                 $this->return[] = array($matches[1], isset($matches[2]) ? $matches[2] : '');
             }
         }
         unset($tags['return']);
     }
     $this->tags = $tags;
 }
 /**
  * Generic class method resolver.
  *
  * @param \ReflectionMethod $method
  * @param ClassMetadata     $classMetadata
  *
  * @return MethodMetadata Resolved method metadata
  */
 protected function resolveMethodMetadata(\ReflectionMethod $method, ClassMetadata $classMetadata) : MethodMetadata
 {
     // Create method metadata instance
     $methodMetadata = $classMetadata->methodsMetadata[$method->name] ?? new MethodMetadata($classMetadata);
     $methodMetadata->name = $method->name;
     $methodMetadata->modifiers = $method->getModifiers();
     $methodMetadata->isPublic = $method->isPublic();
     /** @var \ReflectionParameter $parameter */
     $parameterMetadata = new ParameterMetadata($classMetadata, $methodMetadata);
     foreach ($method->getParameters() as $parameter) {
         $parameterMetadata = $methodMetadata->parametersMetadata[$parameter->name] ?? clone $parameterMetadata;
         $parameterMetadata->name = $parameter->name;
         $parameterMetadata->typeHint = (string) $parameter->getType();
         // Store parameters metadata in method metadata
         $methodMetadata->parametersMetadata[$parameterMetadata->name] = $parameterMetadata;
     }
     // Store method metadata in class metadata
     return $classMetadata->methodsMetadata[$methodMetadata->name] = $methodMetadata;
 }
Example #10
0
function add_class($class_name, $flags)
{
    global $classes, $internal_arginfo;
    $lc = strtolower($class_name);
    $class = new \ReflectionClass($class_name);
    if ($class->isFinal()) {
        $flags |= \ast\flags\CLASS_FINAL;
    }
    if ($class->isAbstract()) {
        $flags |= \ast\flags\CLASS_ABSTRACT;
    }
    $classes[$lc] = ['file' => 'internal', 'conditional' => false, 'flags' => $flags, 'lineno' => 0, 'endLineno' => 0, 'name' => $class_name, 'docComment' => '', 'traits' => []];
    foreach ($class->getDefaultProperties() as $name => $value) {
        $prop = new \ReflectionProperty($class_name, $name);
        $classes[$lc]['properties'][strtolower($name)] = ['flags' => $prop->getModifiers(), 'name' => $name, 'lineno' => 0, 'value' => $value];
    }
    foreach ($class->getConstants() as $name => $value) {
        $classes[$lc]['constants'][strtolower($name)] = ['name' => $name, 'lineno' => 0, 'value' => $value];
    }
    foreach ($class->getMethods() as $method) {
        $meth = new \ReflectionMethod($class_name, $method->name);
        $required = $meth->getNumberOfRequiredParameters();
        $optional = $meth->getNumberOfParameters() - $required;
        $lmname = strtolower($method->name);
        $classes[$lc]['methods'][$lmname] = ['file' => 'internal', 'conditional' => false, 'flags' => $meth->getModifiers(), 'lineno' => 0, 'endLineno' => 0, 'name' => $method->name, 'docComment' => '', 'required' => $required, 'optional' => $optional, 'ret' => null];
        $arginfo = null;
        if (!empty($internal_arginfo["{$class_name}::{$method->name}"])) {
            $arginfo = $internal_arginfo["{$class_name}::{$method->name}"];
            $classes[$lc]['methods'][$lmname]['ret'] = $arginfo[0];
        }
        foreach ($method->getParameters() as $param) {
            $flags = 0;
            if ($param->isPassedByReference()) {
                $flags |= \ast\flags\PARAM_REF;
            }
            if ($param->isVariadic()) {
                $flags |= \ast\flags\PARAM_VARIADIC;
            }
            $classes[$lc]['methods'][strtolower($method->name)]['params'][] = ['file' => 'internal', 'flags' => $flags, 'lineno' => 0, 'name' => $param->name, 'type' => empty($arginfo) ? null : next($arginfo), 'def' => null];
        }
    }
}
Example #11
0
function writeMethod(ReflectionMethod $method, ReflectionClass $class)
{
    if ($method->getDeclaringClass() != $class) {
        return "";
    }
    $acc = $method->getModifiers();
    $func = "";
    if ($acc & ReflectionMethod::IS_STATIC) {
        $func .= "static ";
    }
    if ($acc & ReflectionMethod::IS_ABSTRACT) {
        $func .= "abstract ";
    }
    if ($acc & ReflectionMethod::IS_FINAL) {
        $func .= "final ";
    }
    if ($acc & ReflectionMethod::IS_PUBLIC) {
        $func .= "public ";
    }
    if ($acc & ReflectionMethod::IS_PROTECTED) {
        $func .= "protected ";
    }
    if ($acc & ReflectionMethod::IS_PRIVATE) {
        $func .= "private ";
    }
    $data = methodData($method);
    $params = $data[1];
    if (empty($params)) {
        $refparams = $method->getParameters();
        if (!empty($refparams)) {
            foreach ($refparams as $param) {
                $params[] = "\$" . $param->name;
            }
        } else {
            for ($i = 0; $i < $method->getNumberOfParameters(); $i++) {
                $params[] = "\$arg{$i}";
            }
        }
    }
    $params = join(",", $params);
    return "{$data['0']}{$func}function {$method->name}({$params}) {}\n";
}
Example #12
0
 function getMethod()
 {
     $method_call = '';
     if (!$this->hasClassName()) {
         if ($this->hasFuncName()) {
             $method_call = $this->funcName();
         }
         //if
     } else {
         if (!$this->hasFuncName()) {
             $method_call = $this->className();
         } else {
             $class = $this->className();
             $method = $this->funcName();
             $method_reflect = new ReflectionMethod($class, $method);
             $method_modifiers = join(' ', Reflection::getModifierNames($method_reflect->getModifiers()));
             $method_caller = '->';
             if (mb_stripos($method_modifiers, 'static') !== false) {
                 $method_caller = '::';
             }
             //if
             $method_call = sprintf('%s %s%s%s', $method_modifiers, $class, $method_caller, $method);
         }
         //if/else
     }
     //if/else
     $method_args = '';
     if ($this->hasFuncArgs()) {
         $arg_list = array();
         foreach ($this->funcArgs() as $arg) {
             if (is_object($arg)) {
                 $arg_list[] = get_class($arg);
             } else {
                 if (is_array($arg)) {
                     $arg_list[] = sprintf('Array(%s)', count($arg));
                 } else {
                     if (is_bool($arg)) {
                         $arg_list[] = $arg ? 'TRUE' : 'FALSE';
                     } else {
                         if (is_null($arg)) {
                             $arg_list[] = 'NULL';
                         } else {
                             if (is_string($arg)) {
                                 $arg_list[] = sprintf('"%s"', $arg);
                             } else {
                                 $arg_list[] = $arg;
                             }
                         }
                     }
                 }
                 //if/else
             }
             //if/else
         }
         //foreach
         $method_args = join(', ', $arg_list);
     }
     //if
     return sprintf('%s(%s)', $method_call, $method_args);
 }
Example #13
0
 /**
  * @return Method[]
  */
 public static function methodListFromReflectionClassAndMethod(Context $context, CodeBase $code_base, \ReflectionClass $class, \ReflectionMethod $method) : array
 {
     $reflection_method = new \ReflectionMethod($class->getName(), $method->name);
     $number_of_required_parameters = $reflection_method->getNumberOfRequiredParameters();
     $number_of_optional_parameters = $reflection_method->getNumberOfParameters() - $number_of_required_parameters;
     $method = new Method($context, $method->name, new UnionType(), $reflection_method->getModifiers(), $number_of_required_parameters, $number_of_optional_parameters);
     return self::methodListFromMethod($method, $code_base);
 }
} catch (TypeError $re) {
    echo "Ok - " . $re->getMessage() . PHP_EOL;
}
try {
    new ReflectionMethod('a', 'b', 'c');
} catch (TypeError $re) {
    echo "Ok - " . $re->getMessage() . PHP_EOL;
}
class C
{
    public function f()
    {
    }
}
$rm = new ReflectionMethod('C', 'f');
var_dump($rm->isFinal(1));
var_dump($rm->isAbstract(1));
var_dump($rm->isPrivate(1));
var_dump($rm->isProtected(1));
var_dump($rm->isPublic(1));
var_dump($rm->isStatic(1));
var_dump($rm->isConstructor(1));
var_dump($rm->isDestructor(1));
var_dump($rm->getModifiers(1));
var_dump($rm->isInternal(1));
var_dump($rm->isUserDefined(1));
var_dump($rm->getFileName(1));
var_dump($rm->getStartLine(1));
var_dump($rm->getEndLine(1));
var_dump($rm->getStaticVariables(1));
var_dump($rm->getName(1));
Example #15
0
 /**
  * Finds the visibility of a ReflectionMethod.
  *
  * @param   object   ReflectionMethod
  * @return  string
  */
 protected function visibility(ReflectionMethod $method)
 {
     $vis = array_flip(Reflection::getModifierNames($method->getModifiers()));
     if (isset($vis['public'])) {
         return 'public';
     }
     if (isset($vis['protected'])) {
         return 'protected';
     }
     if (isset($vis['private'])) {
         return 'private';
     }
     return FALSE;
 }
Example #16
0
function create_markup_to_modifiers(ReflectionMethod $method)
{
    /* {{{ */
    $modifiers = Reflection::getModifierNames($method->getModifiers());
    $markup = '';
    if ($modifiers) {
        foreach ($modifiers as $modifier) {
            $markup .= '<modifier>' . $modifier . '</modifier> ';
        }
    }
    return $markup;
}
Example #17
0
 /**
  * Is this a testable method?
  *
  * @param string            $className        Class name
  * @param \ReflectionMethod $reflectionMethod Reflection method
  *
  * @return boolean False if method should not be counted
  */
 protected function isTestableMethod($className, $reflectionMethod)
 {
     $method = $reflectionMethod->getName();
     $modifiers = $reflectionMethod->getModifiers();
     if ($method === $className || $modifiers !== \ReflectionMethod::IS_PUBLIC || in_array($method, self::$magicMethods)) {
         return false;
     }
     return true;
 }
Example #18
0
 /**
  * Create a syntax highlighted diagram of class functions, and optionally the current output of each method.
  * Only use the autofire if you are sure ALL METHODS perform a non-permanent functions.
  *
  * --== WARNING, USING AUTOFIRE IS DANGEROUS AND CAN DESTROY DATA PERMANENTLY ==--
  *
  * For instance,  autofiring a function called delete_all_users() ...will do exactly that!
  *
  * You have been warned!
  *
  * @param   object   $obj       The object to explore.
  * @param   boolean  $autofire  Fire each method, to acertain its current return value.
  * @return  [type]              [description]
  */
 public static function methods($obj, $autofire = false)
 {
     echo self::$is_themed ? '' : self::$theme;
     $methods = get_class_methods($obj);
     asort($methods);
     echo "<pre class='obj_explorer'>" . PHP_EOL;
     self::classes($obj);
     $cnt = 0;
     foreach ($methods as $m) {
         echo "<div class='method'>";
         $fnc = new \ReflectionMethod($obj, $m);
         $num = $fnc->getNumberOfParameters();
         $req = $fnc->getNumberOfRequiredParameters();
         $arg = $fnc->getParameters();
         $mod = implode(' ', \Reflection::getModifierNames($fnc->getModifiers())) . ' ';
         $lin = self::get_func_url($fnc->getStartLine(), $fnc->getEndLine(), $fnc->getFileName());
         $exp = $fnc->getEndLine();
         $dbk = $fnc->getDocComment();
         $nam = "function <b id='{$m}' class='nam'>{$m}</b>";
         # Parse method arguments
         if ($num > 0) {
             $arg = implode($arg, ', ');
             preg_match_all('/\\[(.*?)\\]/', $arg, $arg);
             $arg = implode($arg[1], ',');
             # Remove optional required tags
             $arg = preg_replace('/<required>|<optional>|<head>/', "", $arg);
             # Strip double spaces
             $arg = preg_replace('/\\s+/', "", $arg);
             # Add nice spacing
             $arg = preg_replace('/,/', ', ', $arg);
             # Add Function brackets
             $arg = "({$arg})";
         } else {
             # No arguments with this function, empty brackets
             $arg = '()';
         }
         # Completed function string
         $function = $mod . $nam . $arg;
         # Docblock
         $dbk = self::clean_docblok($dbk);
         # Convert tabs to space
         $dbk = preg_replace('/\\t+/', '    ', $dbk);
         # Realign offset offset docbloks
         $dbk = preg_replace('/\\s\\s+\\*/', "\n *", $dbk);
         # Completed docblok string
         $dokblock = $dbk;
         # Return Defaults
         $result = 'autofire disabled ';
         $type = 'safemode';
         # Parse return value
         if ($autofire) {
             if ($req) {
                 $result = "<b class='com'>...Untested {$req} required argument(s) needed</b>";
             } else {
                 $result = $obj->{$m}();
                 $type = gettype($result);
                 if ($type === "boolean") {
                     $type = AlpStrings::boolstr($result);
                     $result = '';
                 }
                 if ($type === "integer") {
                 }
                 if ($type === "double") {
                 }
                 if ($type === "string") {
                     $result = "'{$result}'";
                 }
                 if ($type === "array") {
                     $result = PHP_EOL . PHP_EOL . '{ARR}' . print_r($result, true) . '{/ARR}';
                 }
                 if ($type === "object") {
                     $result = 'object';
                     #recurse!
                 }
                 if ($type === "resource") {
                     $result = $type;
                 }
                 if ($type === "NULL") {
                     $result = "<b class='com'>...Check page src for possible function echo</b>";
                 }
                 if ($type === "unknown type") {
                     $result = $type;
                 }
             }
         }
         #divider and Line Info
         # Completed return string
         $result = "<b class='ops'>" . trim("Returned </b>(<b class='dec'>{$type}</b>)") . " {$result}";
         $method_info = $dokblock . PHP_EOL . PHP_EOL . $function . PHP_EOL . PHP_EOL . $result;
         $method_info = Syntax::php($method_info, 'all');
         echo $lin;
         echo $method_info;
         echo "</div>";
     }
     echo '</pre>';
     return;
     /*
     	#echo implode(' ', Reflection::getModifierNames($fnc->getModifiers())).PHP_EOL;
     
     	#echo 'getParameters()                 : '.print_r(         $fnc->getParameters()).PHP_EOL;
     	#echo 'getStaticVariables()            : '.print_r(         $fnc->getStaticVariables()).PHP_EOL;
     	#echo 'isAbstract()                    : '.AT::boolstr( $fnc->isAbstract()).PHP_EOL;
     	#echo 'isConstructor()                 : '.AT::boolstr( $fnc->isConstructor()).PHP_EOL;
     	#echo 'isDestructor()                  : '.AT::boolstr( $fnc->isDestructor()).PHP_EOL;
     	#echo 'isFinal()                       : '.AT::boolstr( $fnc->isFinal()).PHP_EOL;
     	#echo 'isPrivate()                     : '.AT::boolstr( $fnc->isPrivate()).PHP_EOL;
     	#echo 'isProtected()                   : '.AT::boolstr( $fnc->isProtected()).PHP_EOL;
     	#echo 'isPublic()                      : '.AT::boolstr( $fnc->isPublic()).PHP_EOL;
     	#echo 'isStatic()                      : '.AT::boolstr( $fnc->isStatic()).PHP_EOL;
     	#echo 'inNamespace()                   : '.AT::boolstr( $fnc->inNamespace()).PHP_EOL;
     	#echo 'isClosure()                     : '.AT::boolstr( $fnc->isClosure()).PHP_EOL;
     	#echo 'isDeprecated()                  : '.AT::boolstr( $fnc->isDeprecated()).PHP_EOL;
     	#echo 'isGenerator()                   : '.AT::boolstr( $fnc->isGenerator()).PHP_EOL;
     	#echo 'isInternal()                    : '.AT::boolstr( $fnc->isInternal()).PHP_EOL;
     	#echo 'isUserDefined()                 : '.AT::boolstr( $fnc->isUserDefined()).PHP_EOL;
     	#echo 'returnsReference()              : '.AT::boolstr( $fnc->returnsReference()).PHP_EOL;
     	#echo 'Name                            : '.                 $fnc->name.PHP_EOL;
     	#echo 'Class                           : '.                 $fnc->class.PHP_EOL;
     	#echo 'getModifiers()                  : '.                 implode(' ', Reflection::getModifierNames($fnc->getModifiers())).PHP_EOL;
     	#echo 'getEndLine()                    : '.                 $fnc->getEndLine().PHP_EOL;
     	#echo 'getNumberOfParameters()         : '.                 $fnc->getNumberOfParameters().PHP_EOL;
     	#echo 'getNumberOfRequiredParameters() : '.                 $fnc->getNumberOfRequiredParameters().PHP_EOL;
     	#echo 'getStartLine()                  : '.                 $fnc->getStartLine().PHP_EOL;
     	#echo 'getDocComment()                 : '.                 $fnc->getDocComment().PHP_EOL;
     	#echo 'getExtensionName()              : '.                 $fnc->getExtensionName().PHP_EOL;
     	#echo 'getFileName()                   : '.                 $fnc->getFileName().PHP_EOL;
     	#echo 'getName()                       : '.                 $fnc->getName().PHP_EOL;
     	#echo 'getNamespaceName()              : '.                 $fnc->getNamespaceName().PHP_EOL;
     	#echo 'getShortName()                  : '.                 $fnc->getShortName().PHP_EOL;
     */
 }
Example #19
0
 /**
  * @param \ReflectionMethod $reflectedMethod
  *
  * @return string
  */
 protected function documentMethodSignature(\ReflectionMethod $reflectedMethod)
 {
     if ($this->processMethodSignature === false) {
         return "";
     }
     $modifiers = implode(' ', \Reflection::getModifierNames($reflectedMethod->getModifiers()));
     $params = implode(', ', array_map(function ($p) {
         return $this->documentParam($p);
     }, $reflectedMethod->getParameters()));
     $signature = "#### *{$modifiers}* {$reflectedMethod->name}({$params})";
     if (is_callable($this->processMethodSignature)) {
         $signature = call_user_func($this->processMethodSignature, $reflectedMethod, $signature);
     }
     return $signature;
 }
Example #20
0
class Counter
{
    private static $c = 0;
    /**
     * Increment counter
     *
     * @final
     * @static
     * @access  public
     * @return  int
     */
    public static final function increment()
    {
        return ++self::$c;
    }
}
// Create an instance of the ReflectionMethod class
$method = new ReflectionMethod('Counter', 'increment');
// Print out basic information
printf("===> The %s%s%s%s%s%s%s method '%s' (which is %s)\n" . "     declared in %s\n" . "     lines %d to %d\n" . "     having the modifiers %d[%s]\n", $method->isInternal() ? 'internal' : 'user-defined', $method->isAbstract() ? ' abstract' : '', $method->isFinal() ? ' final' : '', $method->isPublic() ? ' public' : '', $method->isPrivate() ? ' private' : '', $method->isProtected() ? ' protected' : '', $method->isStatic() ? ' static' : '', $method->getName(), $method->isConstructor() ? 'the constructor' : 'a regular method', $method->getFileName(), $method->getStartLine(), $method->getEndline(), $method->getModifiers(), implode(' ', Reflection::getModifierNames($method->getModifiers())));
echo "\n";
// Print documentation comment
printf("---> Documentation:\n %s\n", var_export($method->getDocComment(), 1));
// Print static variables if existant
if ($statics = $method->getStaticVariables()) {
    printf("---> Static variables: %s\n", var_export($statics, 1));
}
echo "\n";
// Invoke the method
printf("---> Invocation results in: ");
var_dump($method->invoke(NULL));
 private function getMethodData(ReflectionMethod $reflectionMethod, $classContent, &$classData)
 {
     //TODO: parse local variable
     $modifiers = Reflection::getModifierNames($reflectionMethod->getModifiers());
     $startLine = $reflectionMethod->getStartLine();
     $endLine = $reflectionMethod->getEndline();
     $parameters = $reflectionMethod->getParameters();
     $docComment = $reflectionMethod->getDocComment();
     if (!$docComment) {
         $docComment = "";
     }
     $parsedComment = $this->parseDocComment($docComment, 'method');
     $out = array();
     $out['params'] = array();
     $out['docComment'] = $this->trimDocComment($docComment);
     $out['inheritdoc'] = $parsedComment['inheritdoc'];
     $out['startLine'] = $startLine;
     $out['endLine'] = $endLine;
     $origin = $reflectionMethod->getDeclaringClass()->getFileName() == false ? "" : $reflectionMethod->getDeclaringClass()->getFileName();
     $origin = $this->normalizePath($origin);
     $out['origin'] = $origin;
     $params = array();
     foreach ($parameters as $parameter) {
         $parameterName = '$' . $parameter->getName();
         try {
             $parameterClass = $parameter->getClass();
         } catch (\Exception $e) {
             $parameterClass = "";
         }
         $parameterType = "";
         //not defined try to find in the doccomment
         if (empty($parameterClass)) {
             if (array_key_exists($parameterName, $parsedComment['params'])) {
                 $parameterType = $parsedComment['params'][$parameterName];
             }
         } else {
             $parameterType = $parameter->getClass()->getName();
         }
         $params[] = $parameterType . ' ' . $parameterName;
         $out['params'][$parameterName] = $parameterType;
     }
     if (array_key_exists('return', $parsedComment) && $parsedComment['return'] != "") {
         $returnType = "";
         $arrayReturn = 0;
         $returnTypes = explode('|', trim($parsedComment['return']));
         foreach ($returnTypes as $rType) {
             if (preg_match('/\\[\\]$/', $rType)) {
                 $arrayReturn = 1;
                 $rType = trim($rType, "[]");
             }
             if (!$this->isScalar($rType)) {
                 $returnType = $rType;
                 if ($returnType[0] == '\\') {
                     $returnType = substr($returnType, 1);
                 }
                 break;
             }
         }
         if (empty($returnType)) {
             $out['return'] = "";
         } else {
             $out['return'] = $this->guessClass($returnType, $classData['namespaces']);
         }
         $out['array_return'] = $arrayReturn;
     }
     $return = empty($parsedComment['return']) ? "none" : $parsedComment['return'];
     $out['signature'] = '(' . join(', ', $params) . ')  : ' . $return;
     foreach ($modifiers as $modifier) {
         $classData['methods']['modifier'][$modifier][] = $reflectionMethod->name;
     }
     $classData['methods']['all'][$reflectionMethod->name] = $out;
 }
Example #22
0
 public function methods($control)
 {
     $methods = array();
     $controller = APPPATH . 'controllers/' . $control . '.php';
     if (file_exists($controller)) {
         include $controller;
         if (class_exists($control, FALSE)) {
             $controller = new $control();
             foreach (get_class_methods($controller) as $method) {
                 if (!in_array($method, $this->system)) {
                     $m = new ReflectionMethod($control, $method);
                     $r = Reflection::getModifierNames($m->getModifiers());
                     if (in_array('public', $r)) {
                         $methods[] = $method;
                     }
                 }
             }
         }
     }
     return $methods;
 }
Example #23
0
 /**
  * Creates the implementation of a single method
  *
  * @param ReflectionMethod $method
  *
  * @return string
  */
 protected function implementMethod(ReflectionMethod $method)
 {
     $modifiers = implode(' ', Reflection::getModifierNames($method->getModifiers() & ~ReflectionMethod::IS_ABSTRACT));
     $reference = $method->returnsReference() ? '&' : '';
     $methodDef = "\n\t{$modifiers} function {$reference}{$method->getName()}({$this->generateMethodParameters($method)})\n\t{\n\t\t\$args = array();\n\t\t{$this->copyMethodParameters($method)}\n\t\t\n\t\t\$funcArgs = func_get_args();\n\t\t\$answer = \$this->__PHAKE_handlerChain->invoke(\$this, '{$method->getName()}', \$funcArgs, \$args);\n\t\t\n\t\tif (\$answer instanceof Phake_Stubber_Answers_IDelegator)\n\t\t{\n\t\t\t\$delegate = \$answer->getAnswer();\n\t\t\t\$callback = \$delegate->getCallBack(\$this, '{$method->getName()}', \$args);\n\t\t\t\$arguments = \$delegate->getArguments('{$method->getName()}', \$args);\n\n\t\t\t\$realAnswer = call_user_func_array(\$callback, \$arguments);\n\t\t\t\$answer->processAnswer(\$realAnswer);\n\t\t\treturn \$realAnswer;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\$returnAnswer = \$answer->getAnswer();\n\t\t\treturn \$returnAnswer;\n\t\t}\n\t}\n";
     return $methodDef;
 }
<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>
 private function GenerateOverridingMethodTemplate(\ReflectionMethod $EntityMethod)
 {
     $MethodTemplate = self::OverriddenMethodTemplate;
     $Modifiers = \Reflection::getModifierNames($EntityMethod->getModifiers());
     $Modifiers[] = 'function';
     if ($EntityMethod->returnsReference()) {
         $Modifiers[] = '&';
     }
     $Modifiers = implode(' ', $Modifiers);
     $Name = $EntityMethod->getName();
     $Parameters = [];
     $ParameterVariables = [];
     foreach ($EntityMethod->getParameters() as $Parameter) {
         $ParameterVariables[] = '$' . $Parameter->getName();
         $Parameters[] = $this->GenerateMethodParameter($Parameter);
     }
     $Parameters = implode(', ', $Parameters);
     $ParameterVariables = implode(', ', $ParameterVariables);
     $MethodTemplate = str_replace('<Modifiers>', $Modifiers, $MethodTemplate);
     $MethodTemplate = str_replace('<Name>', $Name, $MethodTemplate);
     $MethodTemplate = str_replace('<Parameters>', $Parameters, $MethodTemplate);
     $MethodTemplate = str_replace('<ParameterVariables>', $ParameterVariables, $MethodTemplate);
     return $MethodTemplate;
 }
Example #26
0
 /**
  * Creates a method code from Reflection
  *
  * @param Method|ParsedMethod $method Reflection for method
  * @param string $body Body of method
  *
  * @return string
  */
 protected function getOverriddenMethod($method, $body)
 {
     $code = preg_replace('/ {4}|\\t/', '', $method->getDocComment()) . "\n" . join(' ', Reflection::getModifierNames($method->getModifiers())) . ' function ' . ($method->returnsReference() ? '&' : '') . $method->name . '(' . join(', ', $this->getParameters($method->getParameters())) . ")\n" . "{\n" . $this->indent($body) . "\n" . "}\n";
     return $code;
 }
Example #27
0
File: util.php Project: nikic/phan
function add_class($class_name)
{
    global $classes, $internal_arginfo, $internal_classvars;
    $lc = strtolower($class_name);
    $class = new \ReflectionClass($class_name);
    $flags = 0;
    if ($class->isFinal()) {
        $flags = \ast\flags\CLASS_FINAL;
    } else {
        if ($class->isInterface()) {
            $flags = \ast\flags\CLASS_INTERFACE;
        } else {
            if ($class->isTrait()) {
                $flags = \ast\flags\CLASS_TRAIT;
            }
        }
    }
    if ($class->isAbstract()) {
        $flags |= \ast\flags\CLASS_ABSTRACT;
    }
    $classes[$lc] = ['file' => 'internal', 'namespace' => $class->getNamespaceName(), 'conditional' => false, 'flags' => $flags, 'lineno' => 0, 'endLineno' => 0, 'name' => $class_name, 'docComment' => '', 'type' => '', 'traits' => []];
    $parent = $class->getParentClass();
    if (!$parent) {
        $classes[$lc]['parent'] = '';
    } else {
        $classes[$lc]['parent'] = $parent->getName();
    }
    foreach ($class->getDefaultProperties() as $name => $value) {
        $type = $internal_classvars[strtolower($class_name)]['properties'][$name] ?? type_map(gettype($value));
        #		echo "{$class_name}::{$name} = ($type) $value\n";
        $prop = new \ReflectionProperty($class_name, $name);
        $classes[$lc]['properties'][strtolower($name)] = ['flags' => $prop->getModifiers(), 'name' => $name, 'lineno' => 0, 'type' => type_map(gettype($value))];
    }
    $classes[$lc]['interfaces'] = $class->getInterfaceNames();
    $classes[$lc]['traits'] = $class->getTraitNames();
    $parents = [];
    $parent = $class->getParentClass();
    if ($parent) {
        $temp = $class;
        while ($parent = $temp->getParentClass()) {
            $parents[] = $parent->getName();
            $parents = array_merge($parents, $parent->getInterfaceNames());
            $temp = $parent;
        }
    }
    $types = [$class_name];
    $types = array_merge($types, $classes[$lc]['interfaces']);
    $types = array_merge($types, $parents);
    $classes[$lc]['type'] = implode('|', array_unique($types));
    foreach ($class->getConstants() as $name => $value) {
        $classes[$lc]['constants'][$name] = ['name' => $name, 'lineno' => 0, 'type' => type_map(gettype($value))];
    }
    foreach ($class->getMethods() as $method) {
        $meth = new \ReflectionMethod($class_name, $method->name);
        $required = $meth->getNumberOfRequiredParameters();
        $optional = $meth->getNumberOfParameters() - $required;
        $lmname = strtolower($method->name);
        $classes[$lc]['methods'][$lmname] = ['file' => 'internal', 'namespace' => $class->getNamespaceName(), 'conditional' => false, 'flags' => $meth->getModifiers(), 'lineno' => 0, 'endLineno' => 0, 'name' => $method->name, 'docComment' => '', 'required' => $required, 'optional' => $optional, 'ret' => null];
        $arginfo = [];
        unset(${"arginfo1"});
        $alt = 1;
        if (!empty($internal_arginfo["{$class_name}::{$method->name}"])) {
            $arginfo = $internal_arginfo["{$class_name}::{$method->name}"];
            $classes[$lc]['methods'][$lmname]['ret'] = $arginfo[0];
            while (!empty($internal_arginfo["{$class_name}::{$method->name} {$alt}"])) {
                $classes[$lc]['methods']["{$lmname} {$alt}"] = $classes[$lc]['methods'][$lmname];
                ${"arginfo{$alt}"} = $internal_arginfo["{$class_name}::{$method->name} {$alt}"];
                unset(${"arginfo" . ($alt + 1)});
                $classes[$lc]['methods']["{$lmname} {$alt}"]['ret'] = ${"arginfo{$alt}"}[0];
                $alt++;
            }
        } else {
            if (!empty($parents)) {
                foreach ($parents as $parent_name) {
                    if (!empty($internal_arginfo["{$parent_name}::{$method->name}"])) {
                        $classes[$lc]['methods']["{$lmname} {$alt}"] = $classes[$lc]['methods'][$lmname];
                        $arginfo = $internal_arginfo["{$parent_name}::{$method->name}"];
                        $classes[$lc]['methods'][$lmname]['ret'] = $arginfo[0];
                        while (!empty($internal_arginfo["{$parent_name}::{$method->name} {$alt}"])) {
                            ${"arginfo{$alt}"} = $internal_arginfo["{$parent_name}::{$method->name} {$alt}"];
                            unset(${"arginfo" . ($alt + 1)});
                            $classes[$lc]['methods']["{$lmname} {$alt}"]['ret'] = ${"arginfo{$alt}"}[0];
                            $alt++;
                        }
                        break;
                    }
                }
            }
        }
        foreach ($method->getParameters() as $param) {
            $alt = 1;
            $flags = 0;
            if ($param->isPassedByReference()) {
                $flags |= \ast\flags\PARAM_REF;
            }
            if ($param->isVariadic()) {
                $flags |= \ast\flags\PARAM_VARIADIC;
            }
            $classes[$lc]['methods'][strtolower($method->name)]['params'][] = ['file' => 'internal', 'flags' => $flags, 'lineno' => 0, 'name' => $param->name, 'type' => empty($arginfo) ? null : next($arginfo), 'def' => null];
            while (!empty(${"arginfo{$alt}"})) {
                $classes[$lc]['methods'][strtolower($method->name) . ' ' . $alt]['params'][] = ['file' => 'internal', 'flags' => $flags, 'lineno' => 0, 'name' => $param->name, 'type' => empty(${"arginfo{$alt}"}) ? null : next(${"arginfo{$alt}"}), 'def' => null];
                $alt++;
            }
        }
    }
}
Example #28
0
 /**
  * Creates the implementation of a single method
  *
  * @param ReflectionMethod $method
  *
  * @return string
  */
 protected function implementMethod(ReflectionMethod $method, $static = false)
 {
     $modifiers = implode(' ', Reflection::getModifierNames($method->getModifiers() & ~ReflectionMethod::IS_ABSTRACT));
     $reference = $method->returnsReference() ? '&' : '';
     if ($static) {
         $context = '__CLASS__';
     } else {
         $context = '$this';
     }
     $docComment = $method->getDocComment() ?: '';
     $methodDef = "\n\t{$docComment}\n\t{$modifiers} function {$reference}{$method->getName()}({$this->generateMethodParameters($method)})\n\t{\n\t\t\$__PHAKE_args = array();\n\t\t{$this->copyMethodParameters($method)}\n\n        \$__PHAKE_info = Phake::getInfo({$context});\n\t\tif (\$__PHAKE_info === null) {\n\t\t    return null;\n\t\t}\n\n\t\t\$__PHAKE_funcArgs = func_get_args();\n\t\t\$__PHAKE_answer = \$__PHAKE_info->getHandlerChain()->invoke({$context}, '{$method->getName()}', \$__PHAKE_funcArgs, \$__PHAKE_args);\n\n\t    \$__PHAKE_callback = \$__PHAKE_answer->getAnswerCallback({$context}, '{$method->getName()}');\n\t    \$__PHAKE_result = call_user_func_array(\$__PHAKE_callback, \$__PHAKE_args);\n\t    \$__PHAKE_answer->processAnswer(\$__PHAKE_result);\n\t    return \$__PHAKE_result;\n\t}\n";
     return $methodDef;
 }
 public static function castMethod(\ReflectionMethod $c, array $a, Stub $stub, $isNested)
 {
     $a[Caster::PREFIX_VIRTUAL . 'modifiers'] = implode(' ', \Reflection::getModifierNames($c->getModifiers()));
     return $a;
 }
Example #30
0
 /**
  * @param  string|object $class
  * @param  string        $method
  *
  * @return int
  */
 private static function getModifiers($class, $method)
 {
     $reflectionClass = new \ReflectionClass($class);
     /**
      * @var \ReflectionClass $reflectionInterfaces
      */
     $reflectionInterfaces = $reflectionClass->getInterfaces();
     $isInterfaceMethod = 0;
     foreach ($reflectionInterfaces as $reflectionInterface) {
         if ($reflectionInterface->hasMethod($method)) {
             $isInterfaceMethod = 1;
         }
     }
     $topMostClass = self::getTopMostClass($reflectionClass);
     $isAbstractMethod = 0;
     if ($topMostClass->isAbstract() && $topMostClass->hasMethod($method)) {
         $isAbstractMethod = 2;
     }
     $reflectionMethod = new \ReflectionMethod($class, $method);
     $visibility = $reflectionMethod->getModifiers();
     if ($isAbstractMethod | $isInterfaceMethod) {
         $visibility = $visibility | Constants::ABSTRACT_ONLY;
     }
     return $visibility;
 }