Completed
Push — master ( 20e80f...9e4566 )
by Joachim
08:10
created

NormalizeLabelsCommand   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 146
Duplicated Lines 15.07 %

Coupling/Cohesion

Components 2
Dependencies 11

Importance

Changes 0
Metric Value
wmc 21
lcom 2
cbo 11
dl 22
loc 146
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 7 1
D execute() 22 87 13
A countryMapping() 0 13 3
A shippingMethodMapping() 0 13 3
A getManager() 0 6 1

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
namespace Loevgaard\PakkelabelsBundle\Command;
4
5
use Assert\Assert;
6
use Doctrine\Common\Persistence\ObjectManager;
7
use League\ISO3166\ISO3166;
8
use Loevgaard\PakkelabelsBundle\Entity\Label;
9
use Loevgaard\PakkelabelsBundle\Entity\ShippingMethodMapping;
10
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
11
use Symfony\Component\Console\Command\LockableTrait;
12
use Symfony\Component\Console\Input\InputInterface;
13
use Symfony\Component\Console\Input\InputOption;
14
use Symfony\Component\Console\Output\OutputInterface;
15
16
class NormalizeLabelsCommand extends ContainerAwareCommand
17
{
18
    use LockableTrait;
19
20
    protected function configure()
21
    {
22
        $this->setName('loevgaard:pakkelabels:normalize-labels')
23
            ->setDescription('Normalizes labels before creation')
24
            ->addOption('limit', 'l', InputOption::VALUE_REQUIRED, 'The number of labels to normalize', 20)
25
        ;
26
    }
27
28
    protected function execute(InputInterface $input, OutputInterface $output)
29
    {
30
        if (!$this->lock($this->getName())) {
31
            $output->writeln('The command is already running in another process.');
32
33
            return 0;
34
        }
35
36
        $limit = (int)$input->getOption('limit');
37
        Assert::that($limit)->integer()->greaterThan(0);
38
39
        $manager = $this->getManager();
40
41
        /** @var Label[] $labels */
42
        $labels = $manager->getRepository('LoevgaardPakkelabelsBundle:Label')->findBy([
43
            'status' => Label::STATUS_PENDING_NORMALIZATION
44
        ], null, $limit);
45
46
        if($output->isVerbose()) {
47
            $output->writeln('Label count: '.count($labels));
48
        }
49
50
        $iso3166 = new ISO3166();
51
52
        foreach ($labels as $label) {
53
            $output->writeln('Normalizing label id: '.$label->getId().' with order id: '.$label->getOrderId(), OutputInterface::VERBOSITY_VERBOSE);
54
55
            // check that countries are valid ISO 3166 alpha 2 codes
56
            $senderCountryValid = false;
57
            try {
58
                $iso3166->alpha2($label->getSenderCountryCode());
59
                $senderCountryValid = true;
60
            } catch (\Exception $e) {}
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
61
62 View Code Duplication
            if(!$senderCountryValid) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
63
                $senderCountry = $this->countryMapping($label->getSenderCountryCode());
64
                if($senderCountry) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $senderCountry of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
65
                    $label->setSenderCountryCode($senderCountry);
66
                } else {
67
                    $output->writeln('Sender country code `'.$label->getSenderCountryCode().'` is not a valid ISO 3166 alpha 2 country code. Create a mapping or change the country manually.', OutputInterface::VERBOSITY_VERBOSE);
68
                    $label->markAsError('Sender country code `'.$label->getSenderCountryCode().'` is not a valid ISO 3166 alpha 2 country code. Create a mapping or change the country manually.');
69
                    $manager->flush();
70
                    continue;
71
                }
72
            }
73
74
            $receiverCountryValid = false;
75
            try {
76
                $iso3166->alpha2($label->getReceiverCountryCode());
77
                $receiverCountryValid = true;
78
            } catch (\Exception $e) {}
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
79
80 View Code Duplication
            if(!$receiverCountryValid) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
81
                $receiverCountry = $this->countryMapping($label->getReceiverCountryCode());
82
                if($receiverCountry) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $receiverCountry of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
83
                    $label->setReceiverCountryCode($receiverCountry);
84
                } else {
85
                    $output->writeln('Receiver country code `'.$label->getReceiverCountryCode().'` is not a valid ISO 3166 alpha 2 country code. Create a mapping or change the country manually.', OutputInterface::VERBOSITY_VERBOSE);
86
                    $label->markAsError('Receiver country code `'.$label->getReceiverCountryCode().'` is not a valid ISO 3166 alpha 2 country code. Create a mapping or change the country manually.');
87
                    $manager->flush();
88
                    continue;
89
                }
90
            }
91
92
            // check that the shipping method is mapped
93
            if($label->getShippingMethod()) {
94
                $shippingMethodMapping = $this->shippingMethodMapping($label->getShippingMethod());
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $shippingMethodMapping is correct as $this->shippingMethodMap...l->getShippingMethod()) (which targets Loevgaard\PakkelabelsBun...shippingMethodMapping()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
95
                if($shippingMethodMapping) {
96
                    $label->setProductCode($shippingMethodMapping->getProductCode());
97
                    if(!empty($shippingMethodMapping->getServiceCodes())) {
98
                        $label->setServiceCodes(join(',', $shippingMethodMapping->getServiceCodes()));
99
                    }
100
                } else {
101
                    $output->writeln('Shipping method `'.$label->getShippingMethod().'` is not mapped. Map it manually.', OutputInterface::VERBOSITY_VERBOSE);
102
                    $label->markAsError('Shipping method `'.$label->getShippingMethod().'` is not mapped. Map it manually.');
103
                    $manager->flush();
104
                    continue;
105
                }
106
            }
107
108
            $label->setStatus(Label::STATUS_PENDING_CREATION);
109
110
            $manager->flush();
111
112
            $output->writeln('Label was normalized', OutputInterface::VERBOSITY_VERBOSE);
113
        }
114
    }
115
116
    /**
117
     * @param string $country
118
     * @return null|string
119
     */
120
    protected function countryMapping(string $country)
121
    {
122
        $manager = $this->getManager();
123
        $countryMapping = $manager->getRepository('LoevgaardPakkelabelsBundle:CountryMapping')->findOneBy([
124
            'source' => $country
125
        ]);
126
127
        if($countryMapping && $countryMapping->getCountryCode()) {
128
            return $countryMapping->getCountryCode();
129
        }
130
131
        return null;
132
    }
133
134
    /**
135
     * @param string $shippingMethod
136
     * @return ShippingMethodMapping|null
137
     */
138
    protected function shippingMethodMapping(string $shippingMethod)
139
    {
140
        $manager = $this->getManager();
141
        $shippingMethodMapping = $manager->getRepository('LoevgaardPakkelabelsBundle:ShippingMethodMapping')->findOneBy([
142
            'source' => $shippingMethod
143
        ]);
144
145
        if($shippingMethodMapping && $shippingMethodMapping->getProductCode()) {
146
            return $shippingMethodMapping;
147
        }
148
149
        return null;
150
    }
151
152
    /**
153
     * @return ObjectManager
154
     */
155
    protected function getManager()
156
    {
157
        $em = $this->getContainer()->get('doctrine')->getManager();
158
159
        return $em;
160
    }
161
}
162