Completed
Push — master ( d6c0fd...e0d2a4 )
by Joachim
12:44
created

NormalizeLabelsCommand::getEntityManager()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 0
1
<?php
2
3
namespace Loevgaard\DandomainAltapayBundle\Command;
4
5
use Doctrine\ORM\EntityManager;
6
use League\ISO3166\ISO3166;
7
use Loevgaard\PakkelabelsBundle\Entity\Label;
8
use Loevgaard\PakkelabelsBundle\Entity\ShippingMethodMapping;
9
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
10
use Symfony\Component\Console\Command\LockableTrait;
11
use Symfony\Component\Console\Input\InputInterface;
12
use Symfony\Component\Console\Output\OutputInterface;
13
14
class NormalizeLabelsCommand extends ContainerAwareCommand
15
{
16
    use LockableTrait;
17
18
    protected function configure()
19
    {
20
        $this->setName('loevgaard:pakkelabels:normalize-labels')
21
            ->setDescription('Normalizes labels before creation')
22
        ;
23
    }
24
25
    protected function execute(InputInterface $input, OutputInterface $output)
26
    {
27
        if (!$this->lock($this->getName())) {
28
            $output->writeln('The command is already running in another process.');
29
30
            return 0;
31
        }
32
33
        $em = $this->getEntityManager();
34
35
        $labels = $em->getRepository('LoevgaardPakkelabelsBundle:Label')->findBy([
36
            'status' => Label::STATUS_PENDING_NORMALIZATION
37
        ], null, 20);
38
39
        $iso3166 = new ISO3166();
40
41
        foreach ($labels as $label) {
42
            // check that countries are valid ISO 3166 alpha 2 codes
43
            $senderCountryValid = false;
44
            try {
45
                $iso3166->alpha2($label->getSenderCountryCode());
46
                $senderCountryValid = true;
47
            } catch (\Exception $e) {}
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
48
49
            if(!$senderCountryValid) {
50
                $senderCountry = $this->countryMapping($label->getSenderCountryCode());
51
                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...
52
                    $label->setSenderCountryCode($senderCountry);
53
                } else {
54
                    $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.');
55
                    $em->flush();
56
                    continue;
57
                }
58
            }
59
60
            $receiverCountryValid = false;
61
            try {
62
                $iso3166->alpha2($label->getReceiverCountryCode());
63
                $receiverCountryValid = true;
64
            } catch (\Exception $e) {}
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
65
66
            if(!$receiverCountryValid) {
67
                $receiverCountry = $this->countryMapping($label->getReceiverCountryCode());
68
                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...
69
                    $label->setReceiverCountryCode($receiverCountry);
70
                } else {
71
                    $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.');
72
                    $em->flush();
73
                    continue;
74
                }
75
            }
76
77
            // check that the shipping method is mapped
78
            if($label->getShippingMethod()) {
79
                $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\DandomainAltap...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...
80
                if($shippingMethodMapping) {
81
                    $label->setProductCode($shippingMethodMapping->getProductCode());
82
                    if(!empty($shippingMethodMapping->getServiceCodes())) {
83
                        $label->setServiceCodes(join(',', $shippingMethodMapping->getServiceCodes()));
84
                    }
85
                } else {
86
                    $label->markAsError('Shipping method `'.$label->getShippingMethod().'` is not mapped. Map it manually.');
87
                    $em->flush();
88
                    continue;
89
                }
90
            }
91
92
            $label->setStatus(Label::STATUS_PENDING_CREATION);
93
94
            $em->flush();
95
        }
96
    }
97
98
    /**
99
     * @param string $country
100
     * @return null|string
101
     */
102
    protected function countryMapping(string $country)
103
    {
104
        $em = $this->getEntityManager();
105
        $countryMapping = $em->getRepository('LoevgaardPakkelabelsBundle:CountryMapping')->findOneBy([
106
            'source' => $country
107
        ]);
108
109
        if($countryMapping && $countryMapping->getCountryCode()) {
110
            return $countryMapping->getCountryCode();
111
        }
112
113
        return null;
114
    }
115
116
    /**
117
     * @param string $shippingMethod
118
     * @return ShippingMethodMapping|null
119
     */
120
    protected function shippingMethodMapping(string $shippingMethod)
121
    {
122
        $em = $this->getEntityManager();
123
        $shippingMethodMapping = $em->getRepository('LoevgaardPakkelabelsBundle:ShippingMethodMapping')->findOneBy([
124
            'source' => $shippingMethod
125
        ]);
126
127
        if($shippingMethodMapping && $shippingMethodMapping->getProductCode()) {
128
            return $shippingMethodMapping;
129
        }
130
131
        return null;
132
    }
133
134
    /**
135
     * @return EntityManager
136
     */
137
    protected function getEntityManager() : EntityManager
138
    {
139
        /** @var EntityManager $em */
140
        $em = $this->getContainer()->get('doctrine')->getManager();
141
142
        return $em;
143
    }
144
}
145