Generate method parameter prototype code

@param \ReflectionParameter $rp

@return string
557396
private static function generateParameterPrototypeCode(\ReflectionParameter $rp) : string
    {
        $param_name = $rp->getName();
        $has_type   = $rp->hasType();
        $type       = $rp->getType();
        $class      = $rp->getClass();
        $optional   = $rp->isOptional();
        $default    = $optional ? self::describeDefault($rp->getDefaultValue()) : '';
        
        $typehint = $has_type ? ($type->isBuiltin() ? "$type" : $class->getShortName()) : '';
        
        $code = $typehint . ' ' . Code::PHP_DOLLAR . $param_name . (!empty($default) ? ' ' . Code::PHP_EQUAL . ' ' . $default : '');
        
        return $code;
    }
866599
private function determineParamValue(\ReflectionParameter $parameter)
    {
        $class = $parameter->getClass();

        if (!empty($class)) {
            // If this is a object we may be able to map it to something in our context
            $className = $class->getName();

            // Determine strong type-based link
            if (isset($this->instances[$className])) {
                return $this->instances[$className];
            }

            // Determine weak type-based link
            if (isset($this->weakLinks[$className])) {
                $lowerClassName = $this->weakLinks[$className];
                return $this->instances[$lowerClassName];
            }
        } else {
            // If this is a primitive type, attempt to determine it by its name
            $varName = $parameter->getName();

            if (isset($this->variablesByName[$varName])) {
                return $this->variablesByName[$varName];
            }
        }

        // We were unable to determine a suitable value based on this context. Pass back its default value if possible.
        if ($parameter->isDefaultValueAvailable()) {
            return $parameter->getDefaultValue();
        }

        // As a final fallback we will primitive pass NULL and let the function deal with it.
        return null;
    }
1036780
private static function getParameterTemplate(\ReflectionMethod $reflectionMethod): string
    {
        $template = '';
        $reflectionParameters = $reflectionMethod->getParameters();
        $paramCount = \count($reflectionParameters);
        foreach ($reflectionParameters as $reflectionParameter) {
            $paramCount--;
            // Parameter type
            $type = $reflectionParameter->getType();
            if ($type !== null) {
                $type = $type->__toString();
                $template .= " $type ";
            }

            // Parameter name
            $paramName = $reflectionParameter->getName();
            if ($reflectionParameter->isPassedByReference()) {
                $template .= " &\${$paramName} ";
            } elseif ($reflectionParameter->isVariadic()) {
                $template .= " ...\${$paramName} ";
            } else {
                $template .= " \${$paramName} ";
            }

            // Parameter default value
            if ($reflectionParameter->isOptional() && $reflectionParameter->isVariadic() === false) {
                $template .= self::getParameterDefaultValue($reflectionParameter);
            }

            if ($paramCount !== 0) {
                $template .= ',';
            }
        }

        return $template;
    }
1142531
private function createCode($namespace, \ReflectionMethod $method)
    {
        $app = $this->application;

        return function (InputInterface $input, OutputInterface $output) use ($namespace, $method, $app) {
            $methodName = $method->getName();

            $client = new Client(Environment::getClient());
            $api    = $client->api(strtolower($namespace));
            $api->setEventDispatcher($app->getDispatcher());

            if (true === $input->hasParameterOption('--no-plugins')) {
                // tells to Api, do not use any plugins
                $api->activatePlugins(false);
            }
            if (true === $input->hasParameterOption('--progress')) {
                $formats = array(
                    'very_verbose' => ' %current%/%max% %percent:3s%% %elapsed:6s% %message%',
                    'very_verbose_nomax' => ' %current% %elapsed:6s% %message%',

                    'debug' => ' %current%/%max% %percent:3s%% %elapsed:6s% %memory:6s% %message%',
                    'debug_nomax' => ' %current% %elapsed:6s% %memory:6s% %message%',
                );
                foreach ($formats as $name => $format) {
                    ProgressBar::setFormatDefinition($name, $format);
                }
                $progress = new ProgressBar($output);
                $progress->setMessage('');

                $api->getEventDispatcher()->addListener(
                    Events::PROGRESS,
                    function (GenericEvent $event) use ($progress) {
                        if ($progress instanceof ProgressBar) {
                            $progress->setMessage(
                                sprintf(
                                    'File %s in progress...',
                                    $event['file']->getRelativePathname()
                                )
                            );
                            $progress->advance();
                        }
                    }
                );
            }

            $args = array();

            foreach ($method->getParameters() as $parameter) {
                if ($parameter->isOptional()) {
                    // option
                    $args[$parameter->getName()] = $input->getOption($parameter->getName());
                } else {
                    // argument
                    $args[$parameter->getName()] = $input->getArgument($parameter->getName());
                }
            }

            if (isset($progress) && $progress instanceof ProgressBar) {
                $progress->start();
            }

            // calls the Api method
            try {
                $response = call_user_func_array(
                    array($api, $methodName),
                    $args
                );
            } catch (\Exception $e) {
                $response = $e;
            }

            if (isset($progress) && $progress instanceof ProgressBar) {
                $progress->finish();
                $progress->clear();
            }
            $output->writeln('');

            // prints response returned
            $classParts      = explode('\\', get_class($api));
            $class           = array_pop($classParts);
            $outputFormatter = str_replace("\\Api\\$class", "\\Output\\$class", get_class($api));

            // handle all Api exceptions when occured
            if ($response instanceof \Exception) {
                if (substr_count($response->getMessage(), "\n") > 0) {
                    // message on multiple lines
                    $fmt = new FormatterHelper;
                    $output->writeln(
                        $fmt->formatBlock(
                            explode("\n", $response->getMessage()),
                            'error'
                        )
                    );
                } else {
                    // message on single line
                    $output->writeln('<error>' . $response->getMessage() . '</error>');
                }
                return;
            }

            if (!method_exists($outputFormatter, $methodName)
                || !is_callable(array($outputFormatter, $methodName))
                || $output->isDebug()
            ) {
                $output->writeln('<debug>Raw response</debug>');
                $output->writeln(print_r($response, true), OutputInterface::OUTPUT_RAW);
                return;
            }

            $result = new $outputFormatter();

            if ($input->hasParameterOption('--format')) {
                 return $output->write($response, OutputInterface::OUTPUT_RAW);
            }
            $result->$methodName($output, $response);
        };
    }
1107599
def _generate_rpc_method(self, method):
        '''
        
        '''
        def _(**kwargs):
            '''
            always use named arguments
            '''
            msg_id = self.get_unique_msg_id()
            params = encode_data(kwargs)
            payload = {
                'method': method,
                'params': params,
                'jsonrpc': '2.0',
                'id': msg_id
            }
            response = requests.post(self.url, data=json.dumps(payload), headers=self.headers).json()
            if ('error' in response):
                if response['error']['code'] == JSONRPC_NO_RESULT:
                    return None
                raise Exception('Got error from RPC server when called "%s" error: %s' % (method, response['error']))
            if 'result' in response:
                result = decode_data(response['result'])
                return result
        return _
979563
function ConfigPrint($fp)
    {
        $rp = $this->rp;
        fprintf($fp, "%s ::=", $rp->lhs->name);
        for ($i = 0; $i <= $rp->nrhs; $i++) {
            if ($i === $this->dot) {
                fwrite($fp,' *');
            }
            if ($i === $rp->nrhs) {
                break;
            }
            $sp = $rp->rhs[$i];
            fprintf($fp,' %s', $sp->name);
            if ($sp->type == PHP_ParserGenerator_Symbol::MULTITERMINAL) {
                for ($j = 1; $j < $sp->nsubsym; $j++) {
                    fprintf($fp, '|%s', $sp->subsym[$j]->name);
                }
            }
        }
    }
960886
protected function generateCallCode($typeName, \ReflectionFunction $ref, $num, array $prepend = [], array $resolvers = NULL)
	{
		$code = '$this->call_' . $num . '(';
		
		foreach($ref->getParameters() as $i => $param)
		{
			if($i != 0)
			{
				$code .= ', ';
			}
			
			if(array_key_exists($i, $prepend))
			{
				$code .= $prepend[$i];
				
				continue;
			}
			
			if($resolvers !== NULL && array_key_exists($param->name, $resolvers))
			{
				$resolver = $resolvers[$param->name];
				
				if($resolver instanceof \Closure)
				{
					$num = count($this->methods);
						
					$ref = new \ReflectionFunction($resolver);
					$sig = $this->generateReplacementMethodSignature($ref, $num);
					$body = $this->extractClosureCode($ref);
					
					$this->methods[] = "\t\t" . $sig . " {\n" . $body . "\n\t\t}";
					
					$code .= $this->generateCallCode($typeName, $ref, $num);
					
					continue;
				}
				elseif($resolver instanceof CompiledCodeFragment)
				{
					$code .= $resolver;
					
					continue;
				}
				
				$code .= var_export($resolver, true);
				
				continue;
			}
			
			if(NULL !== ($ptype = $this->getParamType($param)))
			{
				if($ptype === InjectionPointInterface::class)
				{
					$code .= '$point';
					
					continue;
				}
				
				$code .= '$this->get(' . var_export($ptype, true) . ', isset($point) ? $point : NULL)';
				
				continue;
			}
			
			if($param->isOptional())
			{
				$code .= $param->isDefaultValueAvailable() ? var_export($param->getDefaultValue(), true) : 'NULL';
				
				continue;
			}
			
			throw new TypeNotFoundException(sprintf('Cannot populate closure param "%s" without type hint or resolver', $param->name));
		}
		
		return $code . ')';
	}
988248
private function getParameterNamesForDecoratedCall(array $parameters) : array
    {
        return array_map(
            static function (ReflectionParameter $parameter) {
                $name = '';

                if (method_exists($parameter, 'isVariadic')) {
                    if ($parameter->isVariadic()) {
                        $name .= '...';
                    }
                }

                return $name . '$' . $parameter->name;
            },
            $parameters
        );
    }
1200628
protected function _getMethodParameters(
        MethodInjection $method = null,
        ReflectionMethod $methodReflection = null,
        array $parameters = []
    ) {
        $args = [];
        if ($methodReflection) {
            foreach ($methodReflection->getParameters() as $index => $parameter) {
                if (array_key_exists($parameter->getName(), $parameters)) {
                    $value = $parameters[$parameter->getName()];
                } elseif ($method && $method->hasParameter($index)) {
                    $value = $method->getParameter($index);
                } else {
                    // If the parameter is optional and wasn't specified,
                    // we take its default value
                    if ($parameter->isOptional()) {
                        $args[] = $this->_getParameterDefaultValue(
                            $parameter,
                            $methodReflection
                        );
                        continue;
                    }

                    throw new DefinitionException(sprintf(
                        "The parameter '%s' of %s::%s has no value defined " .
                        "or guessable",
                        $parameter->getName(),
                        $methodReflection->getDeclaringClass()->getName(),
                        $methodReflection->getName()
                    ));
                }

                if ($value instanceof ObjectDefinition\EntryReference) {
                    $args[] = $this->_container->get($value->getName());
                } else {
                    $args[] = $value;
                }
            }
        }
        return $args;
    }
862521
protected static function _generateSignature($method)
    {
        $params = [];
        $isVariadic = Suite::$PHP >= 7 ? $method->isVariadic() : false;

        foreach ($method->getParameters() as $num => $parameter) {
            $typehint = Inspector::typehint($parameter);
            $name = $parameter->getName();
            $name = ($name && $name !== '...') ? $name : 'param' . $num;
            $reference = $parameter->isPassedByReference() ? '&' : '';
            $default = '';
            if ($parameter->isDefaultValueAvailable()) {
                $default = var_export($parameter->getDefaultValue(), true);
                $default = ' = ' . preg_replace('/\s+/', '', $default);
            } elseif ($parameter->isOptional()) {
                if ($isVariadic && $parameter->isVariadic()) {
                    $reference = '...';
                    $default = '';
                } else {
                    $default = ' = NULL';
                }
            }
            $allowsNull = '';
            $typehint = $typehint ? $typehint . ' ' : $typehint;
            if (Suite::$PHP >= 7) {
                $type = $parameter->getType();
                if ($type && method_exists($type, 'allowsNull') && $type->allowsNull()) {
                    $allowsNull = '?';
                }
            }
            $params[] = "{$allowsNull}{$typehint}{$reference}\${$name}{$default}";
        }
        return join(', ', $params);
    }
847577
protected function getPhpdoc($method)
    {

        $reflect = false;
        
        foreach($this->served_classes as $class){
            if (\method_exists($class, $method)) {
                $reflect = new \ReflectionMethod($class, $method);
                break;
            }
        
        }
        
        $response = new \stdClass();
        
         if(!$reflect){
            $response->error = new \sb\JSON\RPC2\Error();
            $response->error->code = -32602;
            $response->error->message = "Invalid method parameters";
            return $response;
        }

        $response->phpdoc = $reflect->getDocComment();

        if (\preg_match("~@return (.*?) (.*?)\*/$~s", $response->phpdoc, $match)) {
            $response->return_type = $match[1];
        } else {
            $response->return_type = 'n/a';
        }

        return $response;
    }
855895
private function generatePhpDocParameters(): void
  {
    $parameters = [];
    foreach ($this->routine['phpdoc']['parameters'] as $parameter)
    {
      $mangledName = $this->nameMangler->getParameterName($parameter['parameter_name']);

      $parameters[] = ['php_name'             => '$'.$mangledName,
                       'description'          => $parameter['description'],
                       'php_type'             => $parameter['php_type'],
                       'data_type_descriptor' => $parameter['data_type_descriptor']];
    }

    $this->enhancePhpDocParameters($parameters);

    if (!empty($parameters))
    {
      // Compute the max lengths of parameter names and the PHP types of the parameters.
      $max_name_length = 0;
      $max_type_length = 0;
      foreach ($parameters as $parameter)
      {
        $max_name_length = max($max_name_length, mb_strlen($parameter['php_name']));
        $max_type_length = max($max_type_length, mb_strlen($parameter['php_type']));
      }

      $this->codeStore->append(' *', false);

      // Generate phpDoc for the parameters of the wrapper method.
      foreach ($parameters as $parameter)
      {
        $format = sprintf(' * %%-%ds %%-%ds %%-%ds %%s', mb_strlen('@param'), $max_type_length, $max_name_length);

        $lines = explode(PHP_EOL, $parameter['description'] ?? '');
        if (!empty($lines))
        {
          $line = array_shift($lines);
          $this->codeStore->append(sprintf($format, '@param', $parameter['php_type'], $parameter['php_name'], $line), false);
          foreach ($lines as $line)
          {
            $this->codeStore->append(sprintf($format, ' ', ' ', ' ', $line), false);
          }
        }
        else
        {
          $this->codeStore->append(sprintf($format, '@param', $parameter['php_type'], $parameter['php_name'], ''), false);
        }

        if ($parameter['data_type_descriptor']!==null)
        {
          $this->codeStore->append(sprintf($format, ' ', ' ', ' ', $parameter['data_type_descriptor']), false);
        }
      }
    }
  }
625681
private static function generateMockClassName(\ReflectionClass $rc) : string
    {
        $src_class_name = $rc->getName();
        $pos = strrpos($src_class_name, '\\');
        if ($pos === false){
            $dest_class_name = $src_class_name;
        }
        else{
            $dest_class_name = substr($src_class_name, $pos + 1);
        }
        return Code::CLASS_PREFIX . $dest_class_name;
    }
321241
protected function getReflectionParameterName(\ReflectionParameter $parameter)
    {
        // parameter is a class
        if ($class = $parameter->getClass()) {
            return $class->getName() . ' \$' . $parameter->getName();
        }

        return $parameter->getName();
    }
202242
public static function getParameterType(\ReflectionParameter $param): ?string
    {
        if (!$param->hasType()) {
            return null;
        }

        $type = $param->getType();

        if ($type === null || $type->isBuiltin()) {
            return null;
        }

        $type = $type->getName();
        $lower = \strtolower($type);

        if ($lower === 'self') {
            return $param->getDeclaringClass()->getName();
        }

        if ($lower === 'parent' && ($parent = $param->getDeclaringClass()->getParentClass())) {
            return $parent->getName();
        }

        return $type;
    }
971741
private function getMethod(\ReflectionMethod $method)
    {
        $methodStmt = $this->factory->method($method->name);
        $params = $method->getParameters();
        foreach ($params as $param) {
            $methodStmt = $this->getMethodStatement($param, $methodStmt);
        }
        $returnType = $method->getReturnType();
        if ($returnType instanceof \ReflectionType) {
            $this->setReturnType($returnType, $methodStmt);
        }
        $methodInsideStatements = $this->getMethodInsideStatement($method);
        $methodStmt->addStmts($methodInsideStatements);

        return $this->addMethodDocComment($methodStmt, $method);
    }
8965
public function handle(\ReflectionParameter $parameter)
    {
        $func = $parameter->getDeclaringFunction();
        $method = new \ReflectionMethod($parameter->getDeclaringClass()->name, $func->name);
        $parameter->getDeclaringFunction()->name;
        $annotations = $this->reader->getMethodAnnotations($method);
        foreach ($annotations as $annotation) {
            if ($annotation instanceof ResourceParam && $annotation->param === $parameter->name) {
                return $this->getResourceParam($annotation->uri);
            }
        }
        (new VoidParamHandler)->handle($parameter);
    }