Passed
Pull Request — master (#26)
by Emanuele
02:59
created

LoadFeatureCommand   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 136
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 8

Test Coverage

Coverage 45.88%

Importance

Changes 0
Metric Value
wmc 16
lcom 2
cbo 8
dl 0
loc 136
ccs 39
cts 85
cp 0.4588
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 17 1
B execute() 0 40 6
B findFeatureNodes() 0 33 6
A getFinderInstance() 0 20 3
1
<?php
2
3
namespace Ae\FeatureBundle\Command;
4
5
use Ae\FeatureBundle\Twig\Node\FeatureNode;
6
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
7
use Symfony\Component\Console\Input\InputArgument;
8
use Symfony\Component\Console\Input\InputInterface;
9
use Symfony\Component\Console\Input\InputOption;
10
use Symfony\Component\Console\Output\OutputInterface;
11
use Symfony\Component\Finder\Finder;
12
use Twig_Node;
13
use Twig_Source;
14
15
/**
16
 * @author Carlo Forghieri <[email protected]>
17
 */
18
class LoadFeatureCommand extends ContainerAwareCommand
19
{
20
    /**
21
     * {@inheritdoc}
22
     */
23 1
    protected function configure()
24
    {
25 1
        $this
26 1
            ->setName('features:load')
27 1
            ->setDescription('Persist new features found in templates')
28 1
            ->addArgument(
29 1
                'path',
30 1
                InputArgument::REQUIRED | InputArgument::IS_ARRAY,
31
                'The path or bundle where to load the features'
32 1
            )
33 1
            ->addOption(
34 1
                'dry-run',
35 1
                null,
36 1
                InputOption::VALUE_NONE,
37
                'Do not persist new features'
38 1
            );
39 1
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44 1
    public function execute(InputInterface $input, OutputInterface $output)
45
    {
46 1
        $container = $this->getContainer();
47 1
        $twig = $container->get('twig');
48 1
        $files = $this->getFinderInstance($input->getArgument('path'));
49
50 1
        $found = [];
51 1
        foreach ($files as $file) {
52
            $tree = $twig->parse($twig->tokenize(new Twig_Source(
53
                file_get_contents($file->getPathname()),
54
                $file->getFilename(),
55
                $file->getPathname()
56
            )));
57
            $tags = $this->findFeatureNodes($tree);
58
59
            if (!$tags) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $tags of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
60
                continue;
61
            }
62
63
            $found = array_merge($found, $tags);
64
65
            foreach ($tags as $tag) {
66
                $output->writeln(sprintf(
67
                    'Found <info>%s</info>.<info>%s</info> in <info>%s</info>',
68
                    $tag['parent'],
69
                    $tag['name'],
70
                    $file->getFilename()
71
                ));
72
            }
73 1
        }
74
75 1
        if ($input->getOption('dry-run')) {
76
            return;
77
        }
78
79 1
        $manager = $container->get('ae_feature.manager');
80 1
        foreach ($found as $tag) {
81
            $manager->findOrCreate($tag['name'], $tag['parent']);
82 1
        }
83 1
    }
84
85
    /**
86
     * Find feature nodes.
87
     *
88
     * @param Twig_Node $node
89
     *
90
     * @return array
91
     */
92 1
    private function findFeatureNodes(Twig_Node $node)
93
    {
94
        $found = [];
95
        $stack = [$node];
96
        while ($stack) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $stack of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
97
            $node = array_pop($stack);
98
            if ($node instanceof FeatureNode) {
99
                $arguments = $node
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Twig_Node as the method getKeyValuePairs() does only exist in the following sub-classes of Twig_Node: Twig_Node_Expression_Array. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
100
                    ->getNode('tests')
101 1
                    ->getNode(0)
102
                    ->getNode('arguments')
103
                    ->getKeyValuePairs();
104
105
                $tag = [];
106
                foreach ($arguments as $argument) {
107
                    $keyAttr = $argument['key']->getAttribute('value');
108
                    $valueAttr = $argument['value']->getAttribute('value');
109
110
                    $tag[$keyAttr] = $valueAttr;
111
                }
112
                $key = md5(serialize($tag));
113
                $found[$key] = $tag;
114
            } else {
115
                foreach ($node as $child) {
116
                    if (null !== $child) {
117
                        $stack[] = $child;
118
                    }
119
                }
120
            }
121
        }
122
123
        return array_values($found);
124
    }
125
126
    /**
127
     * Gets a Finder instance with required paths.
128
     *
129
     * @param array $dirsOrBundles Required directories or bundles
130
     *
131
     * @return Finder
132
     */
133 1
    private function getFinderInstance(array $dirsOrBundles)
134
    {
135 1
        $finder = new Finder();
136 1
        $kernel = $this
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Console\Application as the method getKernel() does only exist in the following sub-classes of Symfony\Component\Console\Application: Symfony\Bundle\FrameworkBundle\Console\Application. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
137 1
            ->getApplication()
138 1
            ->getKernel();
139
140 1
        foreach ($dirsOrBundles as $dirOrBundle) {
141 1
            if (isset($kernel->getBundles()[$dirOrBundle])) {
142
                $bundle = $kernel->getBundle($dirOrBundle);
143
                $dirOrBundle = $bundle->getPath().'/Resources/views/';
144
            }
145
146 1
            $finder->in($dirOrBundle);
147 1
        }
148
149
        return $finder
150 1
            ->files()
151 1
            ->name('*.twig');
152
    }
153
}
154