Пример #1
0
 private static function docBlockParser()
 {
     static $docBlockParser = null;
     if ($docBlockParser === null) {
         $docBlockParser = DocBlockFactory::createInstance();
     }
     return $docBlockParser;
 }
Пример #2
0
 /**
  * Formatar float para o número de casas decimais correto.
  * @param $nome
  * @param $valor
  * @return string
  */
 protected function formatar($nome, $valor)
 {
     $ref = new \ReflectionProperty(get_class($this), $nome);
     $factory = DocBlockFactory::createInstance();
     $info = $factory->create($ref->getDocComment());
     // Pegar o tipo da variavel
     $tipo = $info->getTagsByName('var');
     $tipo = count($tipo) == 0 ? 'string' : $tipo[0]->getType();
     $tipo = strtolower($tipo);
     switch ($tipo) {
         case 'string':
         case 'string|null':
         case '\\string':
         case '\\string|null':
             $valor = str_replace(['@'], ['#1#'], utf8_encode($valor));
             // Ignorar alguns caracteres no ascii
             $valor = Str::ascii($valor);
             $valor = str_replace(['&'], ['e'], $valor);
             $valor = str_replace(['#1#'], ['@'], $valor);
             // Retornar caracteres ignorados
             $valor = Str::upper($valor);
             $valor = trim($valor);
             // Max
             $max = $info->getTagsByName('max');
             if (count($max) > 0) {
                 $max = intval($max[0]->getDescription()->render());
                 $valor = trim(substr($valor, 0, $max));
             }
             return $valor;
         case 'float|null':
         case 'float':
             $dec = $info->getTagsByName('dec');
             if (count($dec) == 0) {
                 return $valor;
             }
             // Valor do @dec
             $dec = $dec[0]->getDescription()->render();
             return number_format($valor, $dec, '.', '');
         case 'datetime':
         case '\\datetime':
         case '\\datetime|null':
         case 'date':
         case 'date|null':
         case '\\date':
         case '\\date|null':
             if (is_int($valor)) {
                 $valor = Carbon::createFromTimestamp($valor);
             }
             if (is_string($valor)) {
                 return $valor;
             }
             $format = in_array($tipo, ['date', 'date|null', '\\date', '\\date|null']) ? 'Y-m-d' : Carbon::ATOM;
             return $valor->format($format);
         default:
             return $valor;
     }
 }
Пример #3
0
 /**
  * creates a Command based on an Api Method.
  *
  * @param string            $name
  * @param \ReflectionMethod $method
  * @param string            $token
  *
  * @return Command
  */
 private function generateCommand($name, \ReflectionMethod $method, $token = null)
 {
     $methodName = $this->transformer->transform($method->getName());
     $command = new Command(strtolower($name . ':' . $methodName));
     $docBlock = DocBlockFactory::createInstance()->create($method->getDocComment());
     $command->setDefinition($this->buildDefinition($method, $token));
     $command->setDescription($docBlock->getSummary());
     $command->setCode($this->createCode($name, $method));
     return $command;
 }
Пример #4
0
 /**
  * Given a function, attempt to find the return type.
  *
  * @param ReflectionFunctionAbstract $function
  * @return Type[]
  */
 public function __invoke(ReflectionFunctionAbstract $function)
 {
     $context = $this->createContextForFunction($function);
     $returnTags = DocBlockFactory::createInstance()->create($function->getDocComment(), new Context($context->getNamespace(), $context->getNamespaceAliases()))->getTagsByName('return');
     foreach ($returnTags as $returnTag) {
         /* @var $returnTag \phpDocumentor\Reflection\DocBlock\Tags\Return_ */
         return (new ResolveTypes())->__invoke(explode('|', $returnTag->getType()), $context);
     }
     return [];
 }
Пример #5
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     //Determine source path
     if ($input->getOption('source')) {
         $source_path = realpath($input->getOption('source'));
     } else {
         $source_path = getcwd();
     }
     if (is_dir($source_path) == false || $source_path == false) {
         throw new \InvalidArgumentException('The source directory is not a directory or cannot be found');
     }
     if (!is_readable($source_path)) {
         throw new \InvalidArgumentException(sprintf('The source directory "%s" is not readable', $source_path));
     }
     //Determine output path
     $output_path = getcwd();
     $factory = DocBlockFactory::createInstance($this->custom_tags);
     $finder = new Finder();
     $finder->in($source_path)->name('*.php');
     foreach ($finder as $file) {
         if ($file->isReadable() == false) {
             continue;
         }
         $contents = file_get_contents($file->getRealPath());
         $tokens = token_get_all($contents);
         foreach ($tokens as $token) {
             if ($token[0] === T_DOC_COMMENT) {
                 try {
                     $docblock = $factory->create($token[1]);
                 } catch (Exception $e) {
                     continue;
                 }
                 if ($this->hasApiTags($docblock) == false) {
                     continue;
                 }
                 if ($this->isValidTemplate($docblock)) {
                     $tag = current($docblock->getTagsByName('api-template'));
                     $this->templates[$tag->getKey()] = $docblock;
                     continue;
                 }
                 if ($this->isValidNode($docblock)) {
                     $this->nodes[] = $docblock;
                     continue;
                 }
             }
         }
     }
     $data = [];
     foreach ($this->nodes as $node) {
         $data[] = $this->buildNodeData($node);
     }
     $file_path = $output_path . DIRECTORY_SEPARATOR . 'inspection_data.js';
     file_put_contents($file_path, json_encode($data, JSON_PRETTY_PRINT));
 }
 public function testGetterSetter()
 {
     $Transformer = new CaseTransformer(new SnakeCase(), new StudlyCaps());
     $data = $this->getMockData();
     /** @var AbstractModel $Model */
     $Model = new $this->modelClass();
     $Model->exchangeArray(json_decode($data));
     $ModelReflection = new \ReflectionClass($this->modelClass);
     $ClassFinder = new ClassFinder('DockerCloud');
     $StaticReflectionParser = new StaticReflectionParser($this->modelClass, $ClassFinder);
     $useStatements = $StaticReflectionParser->getUseStatements();
     foreach ($ModelReflection->getProperties(\ReflectionProperty::IS_PROTECTED) as $ReflectionProperty) {
         // Parse @var tag
         $DockBlock = DocBlockFactory::createInstance()->create($ReflectionProperty->getDocComment());
         $this->assertTrue($DockBlock->hasTag('var'));
         /**
          * @var Var_ $VarTag
          */
         $VarTag = $DockBlock->getTagsByName('var')[0];
         $varTypes = explode('|', $VarTag->getType()->__toString());
         //echo $VarTag . PHP_EOL;
         $foundMatchVarTypeCount = 0;
         foreach ($varTypes as $varType) {
             // Get value by using getter method
             $getterMethodName = $Transformer->transform($ReflectionProperty->getName());
             if ('bool' == $varType || 'boolean' == $varType) {
                 $getterMethodName = 'is' . $getterMethodName;
             } else {
                 $getterMethodName = 'get' . $getterMethodName;
             }
             if (!method_exists($Model, $getterMethodName)) {
                 continue;
             }
             $value = $Model->{$getterMethodName}();
             if (strpos($varType, '[]') && is_array($value)) {
                 $value = array_pop($value);
             }
             // If there's no actual value we cannot really validate it...
             $varType = str_replace('[]', '', $varType);
             if (strpos($varType, '\\') === 0) {
                 $varType = substr($varType, 1);
             }
             $foundMatchVarType = $this->validateInternalType($varType, $value);
             if (is_null($foundMatchVarType)) {
                 $foundMatchVarType = $this->validateImportedType($varType, $value, $useStatements);
             }
             if ($foundMatchVarType) {
                 $foundMatchVarTypeCount++;
             }
         }
         self::assertTrue($foundMatchVarTypeCount > 0, sprintf("[%s] haven't getter method.", $ReflectionProperty->getName()));
     }
 }
Пример #7
0
 public static function generate(Reflectable $object)
 {
     static::$object = $object;
     static::$reflection = $object::getReflection();
     $factory = DocBlockFactory::createInstance();
     $docblock = $factory->create(static::$reflection->getDocComment());
     if ($docblock->hasTag('property')) {
         $properties = $docblock->getTagsByName('property');
         foreach ($properties as $property) {
             static::renderField($property);
         }
     }
 }
Пример #8
0
 /**
  * Given a function and parameter, attempt to find the type of the parameter.
  *
  * @param ReflectionFunctionAbstract $function
  * @param ParamNode $node
  * @return Type[]
  */
 public function __invoke(ReflectionFunctionAbstract $function, ParamNode $node)
 {
     $context = $this->createContextForFunction($function);
     $docBlock = DocBlockFactory::createInstance()->create($function->getDocComment(), new Context($context->getNamespace(), $context->getNamespaceAliases()));
     $paramTags = $docBlock->getTagsByName('param');
     foreach ($paramTags as $paramTag) {
         /* @var $paramTag \phpDocumentor\Reflection\DocBlock\Tags\Param */
         if ($paramTag->getVariableName() === $node->name) {
             return (new ResolveTypes())->__invoke(explode('|', $paramTag->getType()), $context);
         }
     }
     return [];
 }
Пример #9
0
 /**
  * Given a property, attempt to find the type of the property.
  *
  * @param ReflectionProperty $reflectionProperty
  * @return Type[]
  */
 public function __invoke(ReflectionProperty $reflectionProperty)
 {
     $contextFactory = new ContextFactory();
     $context = $contextFactory->createForNamespace($reflectionProperty->getDeclaringClass()->getNamespaceName(), $reflectionProperty->getDeclaringClass()->getLocatedSource()->getSource());
     $docBlock = DocBlockFactory::createInstance()->create($reflectionProperty->getDocComment(), new Context($context->getNamespace(), $context->getNamespaceAliases()));
     /* @var \phpDocumentor\Reflection\DocBlock\Tags\Var_ $varTag */
     $resolvedTypes = [];
     $varTags = $docBlock->getTagsByName('var');
     foreach ($varTags as $varTag) {
         $resolvedTypes = array_merge($resolvedTypes, (new ResolveTypes())->__invoke(explode('|', $varTag->getType()), $context));
     }
     return $resolvedTypes;
 }
Пример #10
0
 /**
  * Get the calls
  *
  * @access public
  * @return array $calls
  */
 public function get_calls()
 {
     $class = new \ReflectionClass($this);
     $methods = $class->getMethods();
     $result = [];
     foreach ($methods as $method) {
         if (strpos($method->name, 'call_') !== 0) {
             continue;
         }
         $method_name = str_replace('call_', '', $method->name);
         $comments = $method->getDocComment();
         $factory = \phpDocumentor\Reflection\DocBlockFactory::createInstance();
         $docblock = $factory->create($comments);
         $result[$method_name] = $docblock;
     }
     ksort($result);
     return $result;
 }
     *
     * This method is used to reconstitute a DocBlock into its original form by the {@see Serializer}. It should
     * feature all parts of the tag so that the serializer can put it back together.
     *
     * @return string
     */
    public function __toString()
    {
        return (string) $this->description;
    }
}
$docComment = <<<DOCCOMMENT
/**
 * This is an example of a summary.
 *
 * @my-tag I have a description
 */
DOCCOMMENT;
// Make a mapping between the tag name `my-tag` and the Tag class containing the Factory Method `create`.
$customTags = ['my-tag' => MyTag::class];
// Do pass the list of custom tags to the Factory for the DocBlockFactory.
$factory = DocBlockFactory::createInstance($customTags);
// You can also add Tags later using `$factory->registerTagHandler()` with a tag name and Tag class name.
// Create the DocBlock
$docblock = $factory->create($docComment);
// Take a look: the $customTagObjects now contain an array with your newly added tag
$customTagObjects = $docblock->getTagsByName('my-tag');
// As an experiment: let's reconstitute the DocBlock and observe that because we added a __toString() method
// to the tag class that we can now also see it.
$serializer = new Serializer();
$reconstitutedDocComment = $serializer->getDocComment($docblock);
 public function __construct(ResourceMetadataFactoryInterface $decorated, DocBlockFactoryInterface $docBlockFactory = null)
 {
     $this->decorated = $decorated;
     $this->docBlockFactory = $docBlockFactory ?: DocBlockFactory::createInstance();
     $this->contextFactory = new ContextFactory();
 }
 /**
  * @covers ::__construct
  * @covers ::createInstance
  * @uses \phpDocumentor\Reflection\DocBlock\StandardTagFactory
  * @uses \phpDocumentor\Reflection\DocBlock\DescriptionFactory
  */
 public function testCreateFactoryUsingFactoryMethod()
 {
     $fixture = DocBlockFactory::createInstance();
     $this->assertInstanceOf(DocBlockFactory::class, $fixture);
 }
Пример #14
0
 /**
  * Creates a DocBlockFactory
  */
 public function __construct()
 {
     $this->docBlockFactory = DocBlockFactory::createInstance();
 }
 function __construct()
 {
     $this->factory = \phpDocumentor\Reflection\DocBlockFactory::createInstance();
 }
<?php

require_once __DIR__ . '/../vendor/autoload.php';
use phpDocumentor\Reflection\DocBlock\Serializer;
use phpDocumentor\Reflection\DocBlockFactory;
$docComment = <<<DOCCOMMENT
/**
 * This is an example of a summary.
 *
 * And here is an example of the description
 * of a DocBlock that can span multiple lines.
 *
 * @see \\phpDocumentor\\Reflection\\DocBlock\\StandardTagFactory
 */
DOCCOMMENT;
$factory = DocBlockFactory::createInstance();
$docblock = $factory->create($docComment);
// Create the serializer that will reconstitute the DocBlock back to its original form.
$serializer = new Serializer();
// Reconstitution is performed by the `getDocComment()` method.
$reconstitutedDocComment = $serializer->getDocComment($docblock);
use Alorel\PHPUnitRetryRunner\Annotations\Tags\SleepTime;
use phpDocumentor\Reflection\DocBlockFactory;
use ReflectionProperty;
/**
 * Makes sure we only perform instantiation of DocBlockFactory once
 *
 * @author Art <*****@*****.**>
 */
final class DocBlockFactoryManager
{
    /**
     * The constructed factory
     *
     * @var DocBlockFactory
     */
    private static $FACTORY;
    /**
     * Return the DocBlockFactory instance
     *
     * @author Art <*****@*****.**>
     * @return DocBlockFactory
     */
    public static final function getFactory()
    {
        return self::$FACTORY;
    }
}
$ref = new ReflectionProperty(DocBlockFactoryManager::class, 'FACTORY');
$ref->setAccessible(true);
$ref->setValue(null, DocBlockFactory::createInstance([RetryCount::NAME => RetryCount::class, SleepTime::NAME => SleepTime::class]));
Пример #18
0
 public function __construct()
 {
     $this->docBlockFactory = DocBlockFactory::createInstance();
     $this->contextFactory = new ContextFactory();
 }
Пример #19
0
 public function __construct(DocBlockFactoryInterface $docBlockFactory = null)
 {
     $this->docBlockFactory = $docBlockFactory ?: DocBlockFactory::createInstance();
     $this->contextFactory = new ContextFactory();
     $this->phpDocTypeHelper = new PhpDocTypeHelper();
 }
 /**
  * @param $instance
  * @param $serviceSpecs
  * @return $this
  * @throws \ObjectivePHP\Primitives\Exception
  */
 public function injectDependencies($instance, $serviceSpecs = null)
 {
     if (is_object($instance)) {
         // call injectors if any
         $this->getInjectors()->each(function ($injector) use($instance, $serviceSpecs) {
             $injector($instance, $this, $serviceSpecs);
         });
         if ($instance instanceof InjectionAnnotationProvider) {
             // automated injections
             $reflectedInstance = new \ReflectionObject($instance);
             $reflectedProperties = $reflectedInstance->getProperties();
             foreach ($reflectedProperties as $reflectedProperty) {
                 $injection = $this->getAnnotationsReader()->getPropertyAnnotation($reflectedProperty, Annotation\Inject::class);
                 if ($injection) {
                     if ($injection->class || !$injection->service) {
                         $className = $injection->getDependency();
                         if (!$className) {
                             // use phpdocumentor to get var type
                             $docblock = DocBlockFactory::createInstance()->create($reflectedProperty);
                             if ($docblock->hasTag('var')) {
                                 $className = (string) $docblock->getTagsByName('var')[0]->getType()->getFqsen();
                             } else {
                                 throw new Exception('Undefined dependency. Use either dependency="<className>|<serviceName>" or "@var $property ClassName"');
                             }
                         }
                         $dependency = new $className();
                         $this->injectDependencies($dependency);
                     } else {
                         if ($injection->service) {
                             $dependency = $this->get($injection->getDependency());
                         } else {
                             throw new Exception('Undefined dependency. Use either dependency="<className>|<serviceNAme>" or "@var $property ClassName"');
                         }
                     }
                     if ($injection->setter) {
                         $setter = $injection->setter;
                         $instance->{$setter}($dependency);
                     } else {
                         if (!$reflectedProperty->isPublic()) {
                             $reflectedProperty->setAccessible(true);
                         }
                         $reflectedProperty->setValue($instance, $dependency);
                         if (!$reflectedProperty->isPublic()) {
                             $reflectedProperty->setAccessible(false);
                         }
                     }
                 }
             }
         }
     }
     return $this;
 }
Пример #21
0
 /**
  * Get the resource description.
  *
  * @return string|null
  */
 public function getDescription()
 {
     $factory = \phpDocumentor\Reflection\DocBlockFactory::createInstance();
     $docblock = $factory->create($this->reflector);
     $text = $docblock->getSummary() . $docblock->getDescription();
     return $text;
 }
Пример #22
0
 /**
  * Getter for mount points and actual controller classes for those.
  *
  * @todo Build a cache for this!
  *
  * @return  array
  */
 private function getMountPoints()
 {
     // Create doc block factory
     $factory = DocBlockFactory::createInstance();
     /**
      * Lambda function to iterate all controller classes to return mount points to each of them.
      *
      * @param   string  $file
      *
      * @return  null|\stdClass
      */
     $iterator = function ($file) use($factory) {
         // Specify controller class name with namespace
         $className = '\\App\\Controllers\\' . str_replace('.php', '', basename($file));
         // Get reflection about controller class
         $reflectionClass = new \ReflectionClass($className);
         // We're not interested about abstract classes
         if ($reflectionClass->isAbstract()) {
             return null;
         }
         // Get 'mountPoint' tags from class comment block
         $tags = $factory->create($reflectionClass->getDocComment())->getTagsByName('mountPoint');
         // Nice, we have one 'mountPoint' tag in comments, so we'll use that
         if (count($tags) === 1) {
             $tag = $tags[0];
             // Normalize mount point name
             $mountPoint = trim(str_replace('@' . $tag->getName(), '', $tag->render()));
             // Create output
             $output = new \stdClass();
             $output->mountPoint = $mountPoint;
             $output->controller = $className;
             return $output;
         }
         return null;
     };
     return array_filter(array_map($iterator, glob($this->app->getRootDir() . 'src/App/Controllers/*.php')));
 }
 public function __construct()
 {
     $this->logger = new NullLogger();
     $this->docBlockFactory = DocBlockFactory::createInstance();
 }
 /**
  * @inheritdoc
  */
 protected function setUp()
 {
     $this->docBlockFactory = DocBlockFactory::createInstance();
 }
 public function createDocBlock()
 {
     $docBlockFactory = \phpDocumentor\Reflection\DocBlockFactory::createInstance();
     $contextFactory = new \phpDocumentor\Reflection\Types\ContextFactory();
     return $docBlockFactory->create($this->reflection, $contextFactory->createFromReflector($this->reflection));
 }