AbstractImportCommand::recupererListeIds()
last analyzed

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
c 0
b 0
f 0
nc 1
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
134
                    return false;
135
                }
136
            }
137
            $this->nombreElementsDejaEnvoye += count($donnees);
138
            if (!empty($this->nombreElementsRestant) && $this->nombreElementsDejaEnvoye >= $this->nombreElementsRestant) {
139
                $this->output->writeln("<info>[INFO]</info>On n'importe pas plus de données", OutputInterface::VERBOSITY_VERBOSE);
140
                break;
141
            }
142
        }
143
    }
144
145
    public function recupererLaListeDesIdsANePasImporter()
146
    {
147
        if (!$this->modeSelection || $this->force) {
148
            return [];
149
        }
150
        // gestion pour le mode date && trigger.
151
        $listeIds = $this->recupererListeIds();
152
153
        return $listeIds;
154
    }
155
156
    protected abstract function recupererListeIds();
0 ignored issues
show
Coding Style introduced by
The abstract declaration must precede the visibility declaration
Loading history...
157
158
159
    public function recupererLIdMinimumAImporter()
160
    {
161
        if ($this->force) {
162
            return 1;
163
        }
164
        // Dans le cas ou l'id est saisi et qu'il s'agit du mode par défaut.
165
        if (empty($this->modeSelection)) {
166
            if ((int)$this->input->getOption("id")) {
167
                return $this->input->getOption("id");
168
            }
169
170
            // On récupère directement dans la base de données / ou webservice
171
            return $this->recupererIdMininimum();
172
        }
173
174
        return 1;
175
    }
176
177
    protected abstract function recupererIdMininimum();
0 ignored issues
show
Coding Style introduced by
The abstract declaration must precede the visibility declaration
Loading history...
178
179
    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...
180
181
    protected abstract function formatageDonnees($row);
0 ignored issues
show
Coding Style introduced by
The abstract declaration must precede the visibility declaration
Loading history...
182
183
    protected function configure()
184
    {
185
        parent::configure();
186
        $this->addOption('mode', '', InputOption::VALUE_OPTIONAL, "[|trigger|date] permet de choisir le mode.")
187
            ->addOption('nombreElements', '', InputOption::VALUE_OPTIONAL, "définit le nombre d'éléments maximum à importer")
188
            ->addOption('nombreParPaquet', '', InputOption::VALUE_OPTIONAL, "définit le nombre d'éléments à envoyer par paquet", 50)
189
            //
190
            ->addOption('force', '', InputOption::VALUE_NONE, 'Permet de reimporter les données; même celles déjà importées')// Depends du mode choisis.
191
            //
192
            ->addOption('id', '', InputOption::VALUE_OPTIONAL, "permet de définir à partir de quel id inclus on importe les données")
193
            ->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)
194
            ->addOption(
195
                'nombreDeJours',
196
                '',
197
                InputOption::VALUE_OPTIONAL,
198
                "définit le nombre de jours à traiter. Si jourMinimum et jourMaximum sont définis la valeur sera le différenciel",
199
                3
200
            )
201
            ->addOption('jourMinimum', '', InputOption::VALUE_OPTIONAL, "définit le premier jour à importer")
202
            ->addOption('jourMaximum', '', InputOption::VALUE_OPTIONAL, "définit le dernier jour à importer, par défaut importe jusqu'à hier inclus");
203
    }
204
205
206
    /**
207
     * Permet de formatter les données au format attendu.
208
     *
209
     * @param $idExterne
210
     * @param $type
211
     * @param $origine
212
     * @param array $data
213
     * @param array $extra
214
     *
215
     * @return array
216
     */
217
    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...
218
    {
219
        $export = [
220
            "idExterne" => $idExterne,
221
            "type" => $type,
222
            "origine" => $origine,
223
            "data" => json_encode($data),
224
        ];
225
226
        return $export;
227
    }
228
}
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...
229