Passed
Push — master ( 54a087...58e0d0 )
by Emanuele
01:14
created

LoadFeatureCommand   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 141
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 10

Test Coverage

Coverage 94.38%

Importance

Changes 0
Metric Value
wmc 18
lcom 2
cbo 10
dl 0
loc 141
ccs 84
cts 89
cp 0.9438
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 17 1
B getFinderInstance() 0 25 5
B execute() 0 40 6
B findFeatureNodes() 0 33 6
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\Bundle\FrameworkBundle\Console\Application;
8
use Symfony\Component\Console\Input\InputArgument;
9
use Symfony\Component\Console\Input\InputInterface;
10
use Symfony\Component\Console\Input\InputOption;
11
use Symfony\Component\Console\Output\OutputInterface;
12
use Symfony\Component\Finder\Finder;
13
use Twig_Node;
14
use Twig_Source;
15
16
/**
17
 * @author Carlo Forghieri <[email protected]>
18
 */
19
class LoadFeatureCommand extends ContainerAwareCommand
20
{
21
    /**
22
     * {@inheritdoc}
23
     */
24 3
    protected function configure()
25
    {
26 3
        $this
27 3
            ->setName('features:load')
28 3
            ->setDescription('Persist new features found in templates')
29 3
            ->addArgument(
30 3
                'path',
31 3
                InputArgument::REQUIRED | InputArgument::IS_ARRAY,
32
                'The path or bundle where to load the features'
33 3
            )
34 3
            ->addOption(
35 3
                'dry-run',
36 3
                null,
37 3
                InputOption::VALUE_NONE,
38
                'Do not persist new features'
39 3
            );
40 3
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45 3
    public function execute(InputInterface $input, OutputInterface $output)
46
    {
47 3
        $container = $this->getContainer();
48 3
        $twig = $container->get('twig');
49 3
        $files = $this->getFinderInstance($input->getArgument('path'));
50
51 3
        $found = [];
52 3
        foreach ($files as $file) {
53 1
            $tree = $twig->parse($twig->tokenize(new Twig_Source(
54 1
                file_get_contents($file->getPathname()),
55 1
                $file->getFilename(),
56 1
                $file->getPathname()
57 1
            )));
58 1
            $tags = $this->findFeatureNodes($tree);
59
60 1
            if (empty($tags)) {
61
                continue;
62
            }
63
64 1
            $found = array_merge($found, $tags);
65
66 1
            foreach ($tags as $tag) {
67 1
                $output->writeln(sprintf(
68 1
                    'Found <info>%s</info>.<info>%s</info> in <info>%s</info>',
69 1
                    $tag['parent'],
70 1
                    $tag['name'],
71 1
                    $file->getFilename()
72 1
                ));
73 1
            }
74 2
        }
75
76 2
        if ($input->getOption('dry-run')) {
77 1
            return;
78
        }
79
80 1
        $manager = $container->get('ae_feature.manager');
81 1
        foreach ($found as $tag) {
82
            $manager->findOrCreate($tag['name'], $tag['parent']);
83 1
        }
84 1
    }
85
86
    /**
87
     * Find feature nodes.
88
     *
89
     * @param Twig_Node $node
90
     *
91
     * @return array
92
     */
93 2
    private function findFeatureNodes(Twig_Node $node)
94
    {
95 1
        $found = [];
96 1
        $stack = [$node];
97 1
        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...
98 1
            $node = array_pop($stack);
99 1
            if ($node instanceof FeatureNode) {
100
                $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...
101 2
                    ->getNode('tests')
102 1
                    ->getNode(0)
103 1
                    ->getNode('arguments')
104 1
                    ->getKeyValuePairs();
105
106 1
                $tag = [];
107 1
                foreach ($arguments as $argument) {
108 1
                    $keyAttr = $argument['key']->getAttribute('value');
109 1
                    $valueAttr = $argument['value']->getAttribute('value');
110
111 1
                    $tag[$keyAttr] = $valueAttr;
112 1
                }
113 1
                $key = md5(serialize($tag));
114 1
                $found[$key] = $tag;
115 1
            } else {
116 1
                foreach ($node as $child) {
117 1
                    if (null !== $child) {
118 1
                        $stack[] = $child;
119 1
                    }
120 1
                }
121
            }
122 1
        }
123
124 1
        return array_values($found);
125
    }
126
127
    /**
128
     * Gets a Finder instance with required paths.
129
     *
130
     * @param array $dirsOrBundles Required directories or bundles
131
     *
132
     * @return Finder
133
     */
134 3
    private function getFinderInstance(array $dirsOrBundles)
135
    {
136 3
        $finder = new Finder();
137 3
        $application = $this->getApplication();
138
139 3
        $kernel = null;
140 3
        $bundles = [];
141 3
        if ($application instanceof Application) {
142 3
            $kernel = $application->getKernel();
143 3
            $bundles = $kernel->getBundles();
144 3
        }
145
146 3
        foreach ($dirsOrBundles as $dirOrBundle) {
147 2
            if (null !== $kernel && isset($bundles[$dirOrBundle])) {
148
                $bundle = $kernel->getBundle($dirOrBundle);
149
                $dirOrBundle = $bundle->getPath().'/Resources/views/';
150
            }
151
152 2
            $finder->in($dirOrBundle);
153 3
        }
154
155
        return $finder
156 3
            ->files()
157 3
            ->name('*.twig');
158
    }
159
}
160