Completed
Push — master ( c5d644...a435b5 )
by Guillaume
02:45
created

AbstractImportCommand   B

Complexity

Total Complexity 41

Size/Duplication

Total Lines 219
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 41
lcom 1
cbo 4
dl 0
loc 219
rs 8.2769
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
F traitement() 0 111 29
A recupererLaListeDesIdsANePasImporter() 0 10 3
recupererListeIds() 0 1 ?
A recupererLIdMinimumAImporter() 0 17 4
recupererIdMininimum() 0 1 ?
selectionDonneesAExporter() 0 1 ?
formatageDonnees() 0 1 ?
A configure() 0 21 1
A genererTableauExport() 0 11 1
A lockerName() 0 7 3

How to fix   Complexity   

Complex Class

Complex classes like AbstractImportCommand often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AbstractImportCommand, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Starkerxp\StructureBundle\Command;
4
5
6
use Symfony\Component\Console\Input\InputOption;
7
use Symfony\Component\Console\Output\OutputInterface;
8
9
abstract class AbstractImportCommand extends LockCommand
10
{
11
    protected $type;
12
    protected $origine;
13
14
    protected $modeSelection;
15
    protected $force = false;
16
    protected $nombreElementsRestant;
17
    protected $nombreElementsParPaquet = 50;
18
    protected $nombreDeMinutes = 5;
19
    protected $dateMin;
20
    protected $dateMax;
21
    protected $nombreElementsDejaEnvoye = 0;
22
    protected $nombreDeJourATraiter = 0;
23
24
    public function lockerName()
25
    {
26
        $modeSelection = $this->input->getOption("mode");
27
        $nomLocker = !in_array($modeSelection, ['trigger', 'date']) ? "" : $modeSelection;
28
29
        return $this->getName().(!empty($nomLocker) ? ":".$nomLocker : "");
30
    }
31
32
    public function traitement()
33
    {
34
        // On commence par déterminer le mode sélection des données.
35
        $modeSelection = $this->input->getOption("mode");
36
        $this->modeSelection = !in_array($modeSelection, ['trigger', 'date']) ? "" : $modeSelection;
37
        $this->force = $this->input->getOption("force");
38
        $this->nombreElementsRestant = $this->input->getOption("nombreElements");
39
        $this->nombreElementsParPaquet = $this->input->getOption("nombreParPaquet");
40
        // Gestion de la configuration pour le mode trigger
41
        if ($this->modeSelection == "trigger" && (int)$this->input->getOption("nombreDeMinutes")) {
42
            $nombreDeMinutes = (int)$this->input->getOption("nombreDeMinutes");
43
            $dateMin = (new \DateTime())->sub(new \DateInterval("PT".$nombreDeMinutes."M"));
44
            $dateMax = new \DateTime();
45
            $this->dateMin = $dateMin->format("Y-m-d H:i:s");
46
            $this->dateMax = $dateMax->format("Y-m-d H:i:s");
47
        }
48
        if ($this->modeSelection == "date") {
49
            $jourMinimum = \DateTime::createFromFormat('Y-m-d', $this->input->getOption("jourMinimum"));
50
            $jourMaximum = \DateTime::createFromFormat('Y-m-d', $this->input->getOption("jourMaximum"));
51
            // On s'assure que les dates soit dans le bon sens.
52
            if (!empty($jourMinimum) && !empty($jourMaximum) && $jourMaximum->format('Y-m-d') < $jourMinimum->format('Y-m-d')) {
53
                $tmp = $jourMaximum;
54
                $jourMaximum = $jourMinimum;
55
                $jourMinimum = $tmp;
56
                unset($tmp);
57
            }
58
            $this->nombreDeJourATraiter = abs((int)$this->input->getOption("nombreDeJours"));
0 ignored issues
show
Documentation Bug introduced by
It seems like abs((int) $this->input->...ption('nombreDeJours')) can also be of type double. However, the property $nombreDeJourATraiter is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
59
            if (empty($jourMinimum) && empty($jourMaximum)) {
60
                // min = j-1-$this->nombreDeJourATraiter max =j-1
61
                $jourMinimum = (new \DateTime())->sub(new \DateInterval("P".($this->nombreDeJourATraiter + 1)."D"));
62
                $jourMaximum = (new \DateTime())->sub(new \DateInterval("P1D"));
63
            } else {
64
                if (!empty($jourMinimum) && empty($jourMaximum)) {
65
                    //  max = jMin+$this->nombreDeJourATraiter
66
                    $jourMaximum = (new \DateTime($jourMinimum->format("Y-m-d")))->add(new \DateInterval("P".$this->nombreDeJourATraiter."D"));
67
                } else {
68
                    if (empty($jourMinimum) && !empty($jourMaximum)) {
69
                        // min = jMax-$this->nombreDeJourATraiter
70
                        $jourMinimum = (new \DateTime($jourMaximum->format("Y-m-d")))->sub(new \DateInterval("P".($this->nombreDeJourATraiter + 1)."D"));
71
                    }
72
                }
73
            }
74
            $this->dateMin = $jourMinimum->format("Y-m-d 00:00:00");
75
            $this->dateMax = $jourMaximum->format("Y-m-d 00:00:00");
76
        }
77
        $this->output->writeln(
78
            "<info>[INFO]</info> Le script va exporter les données par paquet de <info>".$this->nombreElementsParPaquet."</info> éléments.",
79
            OutputInterface::VERBOSITY_VERBOSE
80
        );
81
        if (!empty($this->nombreElementsRestant)) {
82
            $this->output->writeln(
83
                "<info>[INFO]</info> Le script s'arrêtera après avoir exporté <info>".$this->nombreElementsRestant."</info> éléments.",
84
                OutputInterface::VERBOSITY_VERBOSE
85
            );
86
        }
87
        if (in_array($this->modeSelection, ["date", "trigger"])) {
88
            $this->output->writeln(
89
                "<info>[INFO]</info> Traitement des données entre le <info>".$this->dateMin."</info> et le <info>".$this->dateMax."</info>.",
90
                OutputInterface::VERBOSITY_VERBOSE
91
            );
92
        }
93
        if ($this->input->getOption("force")) {
94
            $this->output->writeln("<info>[INFO]</info> Le script renverra <info>TOUTES LES DONNEES</info>, y compris celles déjà envoyées.", OutputInterface::VERBOSITY_VERBOSE);
95
        }
96
        $listeIdsANePasImporter = $this->recupererLaListeDesIdsANePasImporter();
97
        $idMinimum = $this->recupererLIdMinimumAImporter(); // Cette valeur est voué à évoluer.
98
        $this->nombreElementsDejaEnvoye = 0;
99
        while (true) {
100
            $limit = $this->nombreElementsParPaquet;
101
            if (!empty($this->nombreElementsRestant)) {
102
                $nombreDeDonneesRestantesAImporter = $this->nombreElementsRestant - $this->nombreElementsDejaEnvoye;
103
                if ($nombreDeDonneesRestantesAImporter < $this->nombreElementsParPaquet) {
104
                    $limit = $nombreDeDonneesRestantesAImporter;
105
                }
106
            }
107
            $donnees = $this->selectionDonneesAExporter($idMinimum, $listeIdsANePasImporter, $limit);
108
            if (empty($donnees)) {
109
                $this->output->writeln("<info>Pas ou plus de données à traiter</info>", OutputInterface::VERBOSITY_VERBOSE);
110
                break;
111
            }
112
            $paquetExport = [];
113
            foreach ($donnees as $row) {
114
                $paquetExport[] = $this->formatageDonnees($row);
115
                $idMinimum = $row["idExterne"];
116
            }
117
            $serviceHttp = $this->getContainer()->get('outils.httpservice.post');
118
            $serviceHttp->enableHttpBuildQuery();
119
            $url = $this->getContainer()->getParameter("starkerxp.api.datas");
120
            $retour = $serviceHttp->envoyer($url, ['batch' => $paquetExport]);
121
            $retourJson = json_decode($retour, true);
122
            if (!empty($retourJson) && !$retourJson['error']) {
123
                $this->output->writeln("<info>Réussit</info>", OutputInterface::VERBOSITY_VERBOSE);
124
            } else {
125
                if (!empty($retourJson) && $retourJson['error']) {
126
                    $this->output->writeln("<info>Échec</info>", OutputInterface::VERBOSITY_VERBOSE);
127
                    foreach ($retourJson['errors'] as $erreur => $nombre) {
128
                        $this->output->writeln("\t<info>".$nombre."</info> ".$erreur, OutputInterface::VERBOSITY_VERBOSE);
129
                    }
130
                } else {
131
                    $this->output->writeln("<error>Une erreur est survenue</error>");
132
                    $this->output->writeln($retour);
133
                    return false;
134
                }
135
            }
136
            $this->nombreElementsDejaEnvoye += count($donnees);
137
            if (!empty($this->nombreElementsRestant) && $this->nombreElementsDejaEnvoye >= $this->nombreElementsRestant) {
138
                $this->output->writeln("<info>[INFO]</info>On n'importe pas plus de données", OutputInterface::VERBOSITY_VERBOSE);
139
                break;
140
            }
141
        }
142
    }
143
144
    public function recupererLaListeDesIdsANePasImporter()
145
    {
146
        if (!$this->modeSelection || $this->force) {
147
            return [];
148
        }
149
        // gestion pour le mode date && trigger.
150
        $listeIds = $this->recupererListeIds();
151
152
        return $listeIds;
153
    }
154
155
    protected abstract function recupererListeIds();
0 ignored issues
show
Coding Style introduced by
The abstract declaration must precede the visibility declaration
Loading history...
156
157
158
    public function recupererLIdMinimumAImporter()
159
    {
160
        if ($this->force) {
161
            return 1;
162
        }
163
        // Dans le cas ou l'id est saisi et qu'il s'agit du mode par défaut.
164
        if (empty($this->modeSelection)) {
165
            if ((int)$this->input->getOption("id")) {
166
                return $this->input->getOption("id");
167
            }
168
169
            // On récupère directement dans la base de données / ou webservice
170
            return $this->recupererIdMininimum();
171
        }
172
173
        return 1;
174
    }
175
176
    protected abstract function recupererIdMininimum();
0 ignored issues
show
Coding Style introduced by
The abstract declaration must precede the visibility declaration
Loading history...
177
178
    protected abstract function selectionDonneesAExporter($idMinimum, $listeIdsANePasImporter, $limit);
0 ignored issues
show
Coding Style introduced by
The abstract declaration must precede the visibility declaration
Loading history...
179
180
    protected abstract function formatageDonnees($row);
0 ignored issues
show
Coding Style introduced by
The abstract declaration must precede the visibility declaration
Loading history...
181
182
    protected function configure()
183
    {
184
        parent::configure();
185
        $this->addOption('mode', '', InputOption::VALUE_OPTIONAL, "[|trigger|date] permet de choisir le mode.")
186
            ->addOption('nombreElements', '', InputOption::VALUE_OPTIONAL, "définit le nombre d'éléments maximum à importer")
187
            ->addOption('nombreParPaquet', '', InputOption::VALUE_OPTIONAL, "définit le nombre d'éléments à envoyer par paquet", 50)
188
            //
189
            ->addOption('force', '', InputOption::VALUE_NONE, 'Permet de reimporter les données; même celles déjà importées')// Depends du mode choisis.
190
            //
191
            ->addOption('id', '', InputOption::VALUE_OPTIONAL, "permet de définir à partir de quel id inclus on importe les données")
192
            ->addOption('nombreDeMinutes','',InputOption::VALUE_OPTIONAL,"permet de modifier le nombre de minute necessaire pour être présent dans la sélection, par défaut 5",5)
193
            ->addOption(
194
                'nombreDeJours',
195
                '',
196
                InputOption::VALUE_OPTIONAL,
197
                "définit le nombre de jours à traiter. Si jourMinimum et jourMaximum sont définis la valeur sera le différenciel",
198
                3
199
            )
200
            ->addOption('jourMinimum', '', InputOption::VALUE_OPTIONAL, "définit le premier jour à importer")
201
            ->addOption('jourMaximum', '', InputOption::VALUE_OPTIONAL, "définit le dernier jour à importer, par défaut importe jusqu'à hier inclus");
202
    }
203
204
205
    /**
206
     * Permet de formatter les données au format attendu.
207
     *
208
     * @param $idExterne
209
     * @param $type
210
     * @param $origine
211
     * @param array $data
212
     * @param array $extra
213
     *
214
     * @return array
215
     */
216
    protected function genererTableauExport($idExterne, $type, $origine, array $data, array $extra = [])
0 ignored issues
show
Unused Code introduced by
The parameter $extra is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
217
    {
218
        $export = [
219
            "idExterne" => $idExterne,
220
            "type"      => $type,
221
            "origine"   => $origine,
222
            "data"      => json_encode($data),
223
        ];
224
225
        return $export;
226
    }
227
}
0 ignored issues
show
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
228