Completed
Pull Request — develop (#92)
by Jaap
02:48
created

File::createFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 1

Importance

Changes 6
Bugs 0 Features 1
Metric Value
c 6
b 0
f 1
dl 0
loc 22
ccs 14
cts 14
cp 1
rs 9.2
cc 1
eloc 14
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * This file is part of phpDocumentor.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 *
8
 * @copyright 2010-2015 Mike van Riel<[email protected]>
9
 * @license   http://www.opensource.org/licenses/mit-license.php MIT
10
 * @link      http://phpdoc.org
11
 */
12
13
14
namespace phpDocumentor\Reflection\Php\Factory;
15
16
use InvalidArgumentException;
17
use phpDocumentor\Reflection\File as FileSystemFile;
18
use phpDocumentor\Reflection\Fqsen;
19
use phpDocumentor\Reflection\Middleware\ChainFactory;
20
use phpDocumentor\Reflection\Middleware\Middleware;
21
use phpDocumentor\Reflection\Php\Factory\File\CreateCommand as FileCreateCommand;
22
use phpDocumentor\Reflection\Php\File as FileElement;
23
use phpDocumentor\Reflection\Php\NodesFactory;
24
use phpDocumentor\Reflection\Php\ProjectFactoryStrategy;
25
use phpDocumentor\Reflection\Php\StrategyContainer;
26
use phpDocumentor\Reflection\Types\Context;
27
use phpDocumentor\Reflection\Types\ContextFactory;
28
use PhpParser\Comment\Doc;
29
use PhpParser\Lexer;
30
use PhpParser\Node;
31
use PhpParser\Node\Stmt\Class_ as ClassNode;
32
use PhpParser\Node\Stmt\Function_ as FunctionNode;
33
use PhpParser\Node\Stmt\Interface_ as InterfaceNode;
34
use PhpParser\Node\Stmt\Namespace_ as NamespaceNode;
35
use PhpParser\Node\Stmt\Trait_ as TraitNode;
36
use PhpParser\NodeAbstract;
37
38
/**
39
 * Strategy to create File element from the provided filename.
40
 * This class supports extra middle wares to add extra steps to the creation process.
41
 */
42
final class File extends AbstractFactory implements ProjectFactoryStrategy
0 ignored issues
show
Complexity introduced by
The class File has a coupling between objects value of 20. Consider to reduce the number of dependencies under 13.
Loading history...
43
{
44
    /**
45
     * @var NodesFactory
46
     */
47
    private $nodesFactory;
48
49
    private $fileMiddleware;
50
51
    /**
52
     * Initializes the object.
53
     *
54
     * @param NodesFactory $nodesFactory
55
     * @param Middleware[] $middleware
56
     */
57 9
    public function __construct(NodesFactory $nodesFactory, $middleware = array())
58
    {
59 9
        parent::__construct();
60 9
        $this->nodesFactory = $nodesFactory;
61
62 9
        $lastCallable = function ($command) {
63 5
            return $this->createFile($command);
64 9
        };
65
66 9
        $this->fileMiddleware = ChainFactory::createExecutionChain($middleware, $lastCallable);
67 9
    }
68
69
    /**
70
     * Returns true when the strategy is able to handle the object.
71
     *
72
     * @param string $file path to check.
73
     * @return boolean
74
     */
75 1
    public function matches($file)
76
    {
77 1
        return $file instanceof FileSystemFile;
78
    }
79
80
    /**
81
     * Creates an File out of the given object.
82
     * Since an object might contain other objects that need to be converted the $factory is passed so it can be
83
     * used to create nested Elements.
84
     *
85
     * @param FileSystemFile $object path to the file to convert to an File object.
86
     * @param StrategyContainer $strategies used to convert nested objects.
87
     * @param Context $context
88
     * @return File
89
     */
90 6
    protected function doCreate($object, StrategyContainer $strategies, Context $context = null)
91
    {
92 6
        $command = new FileCreateCommand($object, $strategies);
93 6
        $middlewareChain = $this->fileMiddleware;
94
95 6
        return $middlewareChain($command);
96
    }
97
98
    /**
99
     * @param CreateCommand $command
100
     * @return FileElement
101
     */
102 5
    private function createFile(FileCreateCommand $command)
103
    {
104 5
        $file = $command->getFile();
105 5
        $code = $file->getContents();
106 5
        $nodes = $this->nodesFactory->create($code);
107
108 5
        $contextFactory = new ContextFactory();
109 5
        $context = $contextFactory->createForNamespace('\\', $code);
110
111 5
        $docBlock = $this->createFileDocBlock(null, $command->getStrategies(), $context, $nodes);
112
113 5
        $result = new FileElement(
114 5
            $file->md5(),
115 5
            $file->path(),
116 5
            $code,
117
            $docBlock
0 ignored issues
show
Bug introduced by
It seems like $docBlock defined by $this->createFileDocBloc...es(), $context, $nodes) on line 111 can also be of type object<PhpParser\Comment\Doc> or object<phpDocumentor\Reflection\Element>; however, phpDocumentor\Reflection\Php\File::__construct() does only seem to accept null|object<phpDocumentor\Reflection\DocBlock>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
118 5
        );
119
120 5
        $this->createElements(new Fqsen('\\'), $nodes, $result, $command->getStrategies());
121
122 5
        return $result;
123
    }
124
125
    /**
126
     * @param Fqsen $namespace
127
     * @param Node[] $nodes
128
     * @param FileElement $file
129
     * @param StrategyContainer $strategies
130
     */
131 5
    private function createElements(Fqsen $namespace, $nodes, FileElement $file, StrategyContainer $strategies)
132
    {
133 5
        $contextFactory = new ContextFactory();
134 5
        $context = $contextFactory->createForNamespace((string)$namespace, $file->getSource());
135 5
        foreach ($nodes as $node) {
136 5
            switch (get_class($node)) {
137 5
                case ClassNode::class:
138 1
                    $strategy = $strategies->findMatching($node);
139 1
                    $class = $strategy->create($node, $strategies, $context);
140 1
                    $file->addClass($class);
0 ignored issues
show
Compatibility introduced by
$class of type object<phpDocumentor\Reflection\Element> is not a sub-type of object<phpDocumentor\Reflection\Php\Class_>. It seems like you assume a concrete implementation of the interface phpDocumentor\Reflection\Element to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
141 1
                    break;
142 4
                case FunctionNode::class:
143 1
                    $strategy = $strategies->findMatching($node);
144 1
                    $function = $strategy->create($node, $strategies, $context);
145 1
                    $file->addFunction($function);
0 ignored issues
show
Compatibility introduced by
$function of type object<phpDocumentor\Reflection\Element> is not a sub-type of object<phpDocumentor\Reflection\Php\Function_>. It seems like you assume a concrete implementation of the interface phpDocumentor\Reflection\Element to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
146 1
                    break;
147 3
                case InterfaceNode::class:
148 1
                    $strategy = $strategies->findMatching($node);
149 1
                    $interface = $strategy->create($node, $strategies, $context);
150 1
                    $file->addInterface($interface);
0 ignored issues
show
Compatibility introduced by
$interface of type object<phpDocumentor\Reflection\Element> is not a sub-type of object<phpDocumentor\Reflection\Php\Interface_>. It seems like you assume a concrete implementation of the interface phpDocumentor\Reflection\Element to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
151 1
                    break;
152 2
                case NamespaceNode::class:
153 1
                    $file->addNamespace($node->fqsen);
0 ignored issues
show
Bug introduced by
Accessing fqsen on the interface PhpParser\Node suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
154 1
                    $this->createElements($node->fqsen, $node->stmts, $file, $strategies);
0 ignored issues
show
Bug introduced by
Accessing fqsen on the interface PhpParser\Node suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
Bug introduced by
Accessing stmts on the interface PhpParser\Node suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
155 1
                    break;
156 1
                case TraitNode::class:
157 1
                    $strategy = $strategies->findMatching($node);
158 1
                    $trait = $strategy->create($node, $strategies, $context);
159 1
                    $file->addTrait($trait);
0 ignored issues
show
Compatibility introduced by
$trait of type object<phpDocumentor\Reflection\Element> is not a sub-type of object<phpDocumentor\Reflection\Php\Trait_>. It seems like you assume a concrete implementation of the interface phpDocumentor\Reflection\Element to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
160 1
                    break;
161 5
            }
162 5
        }
163 5
    }
164
165
    /**
166
     * @param Doc $docBlock
167
     * @param StrategyContainer $strategies
168
     * @param Context $context
169
     * @param Node[] $nodes
170
     * @return null|\phpDocumentor\Reflection\Element
171
     */
172 5
    protected function createFileDocBlock(
173
        Doc $docBlock = null,
174
        StrategyContainer $strategies = null,
175
        Context $context = null,
176 1
        $nodes = array()
177
    ) {
178
        /** @var NodeAbstract $node */
179 5
        $node = current($nodes);
180 5
        if ($node instanceof Node) {
181 5
            $comments = $node->getAttribute('comments');
182 5
            if (is_array($comments)) {
183
                if ($node instanceof NamespaceNode) {
184
                    $docBlock = $this->createDocBlock($strategies, current($comments), $context);
0 ignored issues
show
Bug introduced by
It seems like $strategies defined by parameter $strategies on line 174 can be null; however, phpDocumentor\Reflection...ctory::createDocBlock() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
185
                } elseif (count($comments) == 2) {
186
                    $docBlock = $this->createDocBlock($strategies, current($comments), $context);
0 ignored issues
show
Bug introduced by
It seems like $strategies defined by parameter $strategies on line 174 can be null; however, phpDocumentor\Reflection...ctory::createDocBlock() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
187
                }
188
            }
189 5
        }
190
191 5
        return $docBlock;
192
    }
193
}
194