Completed
Pull Request — master (#2014)
by Gabriel
15:07
created

GeneratePersistentCollectionsCommand   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 94
Duplicated Lines 24.47 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 7
dl 23
loc 94
ccs 0
cts 73
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 23 23 1
C execute() 0 61 10

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\ODM\MongoDB\Tools\Console\Command;
6
7
use Doctrine\ODM\MongoDB\Tools\Console\MetadataFilter;
8
use InvalidArgumentException;
9
use Symfony\Component\Console;
10
use Symfony\Component\Console\Input\InputArgument;
11
use Symfony\Component\Console\Input\InputOption;
12
use const PHP_EOL;
13
use function assert;
14
use function count;
15
use function file_exists;
16
use function is_array;
17
use function is_dir;
18
use function is_writable;
19
use function mkdir;
20
use function realpath;
21
use function sprintf;
22
23
/**
24
 * Command to (re)generate the persistent collection classes used by doctrine.
25
 */
26
class GeneratePersistentCollectionsCommand extends Console\Command\Command
27
{
28
    /**
29
     * @see Console\Command\Command
30
     */
31 View Code Duplication
    protected function configure()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
32
    {
33
        $this
34
            ->setName('odm:generate:persistent-collections')
35
            ->setDescription('Generates persistent collection classes for custom collections.')
36
            ->setDefinition([
37
                new InputOption(
38
                    'filter',
39
                    null,
40
                    InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
41
                    'A string pattern used to match documents that should be processed.'
42
                ),
43
                new InputArgument(
44
                    'dest-path',
45
                    InputArgument::OPTIONAL,
46
                    'The path to generate your proxy classes. If none is provided, it will attempt to grab from configuration.'
47
                ),
48
            ])
49
            ->setHelp(<<<EOT
50
Generates persistent collection classes for custom collections.
51
EOT
52
            );
53
    }
54
55
    /**
56
     * @see Console\Command\Command
57
     */
58
    protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
59
    {
60
        $filter = $input->getOption('filter');
61
        assert(is_array($filter));
62
63
        $dm = $this->getHelper('documentManager')->getDocumentManager();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Console\Helper\HelperInterface as the method getDocumentManager() does only exist in the following implementations of said interface: Doctrine\ODM\MongoDB\Too...r\DocumentManagerHelper.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
64
65
        $metadatas = $dm->getMetadataFactory()->getAllMetadata();
66
        $metadatas = MetadataFilter::filter($metadatas, $filter);
67
        $destPath  = $input->getArgument('dest-path');
68
69
        // Process destination directory
70
        if ($destPath === null) {
71
            $destPath = $dm->getConfiguration()->getPersistentCollectionDir();
72
        }
73
74
        if (! is_dir($destPath)) {
75
            mkdir($destPath, 0775, true);
76
        }
77
78
        $destPath = realpath($destPath);
79
        assert($destPath !== false);
80
81
        if (! file_exists($destPath)) {
82
            throw new InvalidArgumentException(
83
                sprintf("Persistent collections destination directory '<info>%s</info>' does not exist.", $destPath)
84
            );
85
        }
86
87
        if (! is_writable($destPath)) {
88
            throw new InvalidArgumentException(
89
                sprintf("Persistent collections destination directory '<info>%s</info>' does not have write permissions.", $destPath)
90
            );
91
        }
92
93
        if (count($metadatas)) {
94
            $generated           = [];
95
            $collectionGenerator = $dm->getConfiguration()->getPersistentCollectionGenerator();
96
            foreach ($metadatas as $metadata) {
97
                $output->write(
98
                    sprintf('Processing document "<info>%s</info>"', $metadata->name) . PHP_EOL
99
                );
100
                foreach ($metadata->getAssociationNames() as $fieldName) {
101
                    $mapping = $metadata->getFieldMapping($fieldName);
102
                    if (empty($mapping['collectionClass']) || isset($generated[$mapping['collectionClass']])) {
103
                        continue;
104
                    }
105
                    $generated[$mapping['collectionClass']] = true;
106
                    $output->write(
107
                        sprintf('Generating class for "<info>%s</info>"', $mapping['collectionClass']) . PHP_EOL
108
                    );
109
                    $collectionGenerator->generateClass($mapping['collectionClass'], $destPath);
110
                }
111
            }
112
113
            // Outputting information message
114
            $output->write(PHP_EOL . sprintf('Persistent collections classes generated to "<info>%s</INFO>"', $destPath) . PHP_EOL);
115
        } else {
116
            $output->write('No Metadata Classes to process.' . PHP_EOL);
117
        }
118
    }
119
}
120