Completed
Push — master ( cf24ba...2baed6 )
by WEBEWEB
02:24
created

OcrProvider::getLocalDirectoryError()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of the core-library package.
5
 *
6
 * (c) 2020 WEBEWEB
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace WBW\Library\Core\ThirdParty\OcrLad\Provider;
13
14
use Psr\Log\LoggerAwareTrait;
15
use Psr\Log\LoggerInterface;
16
use WBW\Library\Core\Model\Attribute\StringHostnameTrait;
17
use WBW\Library\Core\Model\Attribute\StringPasswordTrait;
18
use WBW\Library\Core\Model\Attribute\StringUsernameTrait;
19
use WBW\Library\Core\Network\FTP\Client\FtpClient;
20
use WBW\Library\Core\Network\FTP\Exception\FtpException;
21
use WBW\Library\Core\Security\Authenticator;
22
use WBW\Library\Core\Security\PasswordAuthentication;
23
use WBW\Library\Core\ThirdParty\OcrLad\Model\IOFile;
24
25
/**
26
 * OCR provider.
27
 *
28
 * @author webeweb <https://github.com/webeweb>
29
 * @package WBW\Library\Core\ThirdParty\OcrLad\Provider
30
 */
31
class OcrProvider {
32
33
    use LoggerAwareTrait;
34
    use StringHostnameTrait;
35
    use StringPasswordTrait;
36
    use StringUsernameTrait;
37
38
    /**
39
     * FTP client.
40
     *
41
     * @var FtpClient
42
     */
43
    private $ftpClient;
44
45
    /**
46
     * Local directory "after".
47
     *
48
     * @var string
49
     */
50
    private $localDirectoryAfter;
51
52
    /**
53
     * Local directory "before".
54
     *
55
     * @var string
56
     */
57
    private $localDirectoryBefore;
58
59
    /**
60
     * Local directory "error".
61
     *
62
     * @var string
63
     */
64
    private $localDirectoryError;
65
66
    /**
67
     * Remote directory "after".
68
     *
69
     * @var string
70
     */
71
    private $remoteDirectoryAfter;
72
73
    /**
74
     * Remote directory "before".
75
     *
76
     * @var string
77
     */
78
    private $remoteDirectoryBefore;
79
80
    /**
81
     * Remote directory "error".
82
     *
83
     * @var string
84
     */
85
    private $remoteDirectoryError;
86
87
    /**
88
     * Constructor.
89
     *
90
     * @param LoggerInterface $logger The logger.
91
     */
92
    public function __construct(LoggerInterface $logger) {
93
        $this->setLogger($logger);
94
        $this->setRemoteDirectoryAfter("/Apres");
95
        $this->setRemoteDirectoryBefore("/Avant");
96
        $this->setRemoteDirectoryError("/Erreur");
97
    }
98
99
    /**
100
     * Destructor.
101
     */
102
    public function __destruct() {
103
104
        if (null !== $this->ftpClient) {
105
106
            $this->getLogger()->info("OCR provider closes the FTP connection", ["_hostname" => $this->getHostname()]);
107
            $this->ftpClient->close();
108
            $this->ftpClient = null;
109
        }
110
    }
111
112
    /**
113
     * Build the file paths.
114
     *
115
     * @param IOFile $file The file.
116
     * @return array Returns the file paths.
117
     */
118
    protected function buildFilePaths(IOFile $file) {
119
        return [
120
            "upload" => $this->getRemoteDirectoryBefore() . "/{${$file->getUniqFilenamePdf()}}",
121
            "remote" => [
122
                implode("/", [$this->getRemoteDirectoryAfter(), $file->getUniqFilenameDer()]),
123
                implode("/", [$this->getRemoteDirectoryAfter(), $file->getUniqFilenamePdf()]),
124
                implode("/", [$this->getRemoteDirectoryAfter(), $file->getUniqFilenameXml()]),
125
            ],
126
            "local"  => [
127
                implode("/", [$this->getLocalDirectoryAfter(), $file->getUniqFilenameDer()]),
128
                implode("/", [$this->getLocalDirectoryAfter(), $file->getUniqFilenamePdf()]),
129
                implode("/", [$this->getLocalDirectoryAfter(), $file->getUniqFilenameXml()]),
130
            ],
131
        ];
132
    }
133
134
    /**
135
     * Delete the remote files.
136
     *
137
     * @return void
138
     * @throws FtpException Throws an FTP exception if an error occurs.
139
     */
140
    public function deleteRemoteFiles() {
141
142
        $provider = $this;
143
144
        /**
145
         * @param string $directory The directory.
146
         * @throws FtpException Throws an FTP excpetion if an error occurs.
147
         */
148
        $deleteClosure = function($directory) use ($provider) {
149
150
            $provider->getLogger()->info("OCR provider list files in a given directory", ["_directory" => $directory]);
151
            $files = $provider->getFtpClient()->nlist($directory);
152
153
            foreach ($files as $current) {
154
155
                $provider->getLogger()->info("OCR provider deletes a file on the FTP server", ["_remote" => $current]);
156
                $provider->getFtpClient()->delete($current);
157
            }
158
        };
159
160
        $deleteClosure($this->getRemoteDirectoryBefore());
161
        $deleteClosure($this->getRemoteDirectoryAfter());
162
        $deleteClosure($this->getRemoteDirectoryError());
163
    }
164
165
    /**
166
     * Get the FTP client.
167
     *
168
     * @return FtpClient Returns the FTP client.
169
     * @throws FtpException Throws an FTP exception if an error occurs.
170
     */
171
    public function getFtpClient() {
172
173
        if (null === $this->ftpClient) {
174
175
            $authentication = new PasswordAuthentication($this->getUsername(), $this->getPassword());
176
            $authenticator  = new Authenticator($this->getHostname(), $authentication);
177
178
            $this->ftpClient = new FtpClient($authenticator);
179
180
            $this->getLogger()->info("OCR provider opens an FTP connection to FTP", ["_hostname" => $this->getHostname()]);
181
            $this->ftpClient->connect();
182
183
            $this->getLogger()->info("OCR provider logs in to the FTP connection", ["_username" => $this->getUsername()]);
184
            $this->ftpClient->login();
185
186
            $this->getLogger()->info("OCR provider turns passive mode on");
187
            $this->ftpClient->pasv(true);
188
        }
189
190
        return $this->ftpClient;
191
    }
192
193
    /**
194
     * Get the local directory "after".
195
     *
196
     * @return string Returns the local directory "after".
197
     */
198
    public function getLocalDirectoryAfter() {
199
        return $this->localDirectoryAfter;
200
    }
201
202
    /**
203
     * Get the local directory "before".
204
     *
205
     * @return string Returns the local directory "before"
206
     */
207
    public function getLocalDirectoryBefore() {
208
        return $this->localDirectoryBefore;
209
    }
210
211
    /**
212
     * Get the local directory "error".
213
     *
214
     * @return string Returns the local directory "error".
215
     */
216
    public function getLocalDirectoryError() {
217
        return $this->localDirectoryError;
218
    }
219
220
    /**
221
     * Get the logger.
222
     *
223
     * @return LoggerInterface Returns the logger.
224
     */
225
    public function getLogger() {
226
        return $this->logger;
227
    }
228
229
    /**
230
     * Ge the remote directory "after".
231
     *
232
     * @return string Returns the remote directory "after".
233
     */
234
    public function getRemoteDirectoryAfter() {
235
        return $this->remoteDirectoryAfter;
236
    }
237
238
    /**
239
     * Get the remote directory "before".
240
     *
241
     * @return string Returns the remote directory "before".
242
     */
243
    public function getRemoteDirectoryBefore() {
244
        return $this->remoteDirectoryBefore;
245
    }
246
247
    /**
248
     * Get the remote directory "error".
249
     *
250
     * @return string Returns the remote directory "error".
251
     */
252
    public function getRemoteDirectoryError() {
253
        return $this->remoteDirectoryError;
254
    }
255
256
    /**
257
     * Scan a file.
258
     *
259
     * @param IOFile $file The I/O file.
260
     * @param int $retry The retry count.
261
     * @param int $wait The waiting time (in seconds) between retries.
262
     * @return bool Returns true in case of success, false otherwise.
263
     * @throws FtpException Throws an FTP exception in case of success, false otherwise.
264
     */
265
    public function scanFile(IOFile $file, $retry = 30, $wait = 5) {
266
267
        $paths = $this->buildFilePaths($file);
268
269
        $this->getLogger()->info("OCR provider upload a file to the FTP server", ["_local" => $file->getPathname(), "_remote" => $paths["before"]]);
270
        $this->getFtpClient()->put($file->getPathname(), $paths["before"]);
271
272
        $provider = $this;
273
274
        /**
275
         * @param string $local The local file.
276
         * @param string $remote The remote file.
277
         */
278
        $downloadClosure = function($local, $remote) use ($provider) {
279
            $provider->getLogger()->info("OCR provider downloads a file  from the FTP server", ["_local" => $local, "_remote" => $remote]);
280
            $provider->getFtpClient()->get($local, $remote);
281
        };
282
283
        $result = false;
284
285
        for ($i = 0; $i < $retry; ++$i) {
286
287
            $files = $this->getFtpClient()->nlist($this->getRemoteDirectoryAfter());
288
            if (false === in_array($paths["remote"], $files)) {
289
290
                $this->getLogger()->info("OCR provider is waiting for...", ["_remote" => $paths["remote"][0]]);
291
                sleep($wait);
292
293
                continue;
294
            }
295
296
            $downloadClosure($paths["local"][0], $paths["remote"][0]);
297
            $downloadClosure($paths["local"][1], $paths["remote"][1]);
298
            $downloadClosure($paths["local"][2], $paths["remote"][2]);
299
300
            $result = true;
301
302
            break;
303
        }
304
305
        if (false === $result) {
306
            $this->getLogger()->info("OCR provider fail to download a file from the FTP server", ["_local" => $paths["local"][0], "_remote" => $paths["remote"][0]]);
307
            $this->getLogger()->info("OCR provider fail to download a file from the FTP server", ["_local" => $paths["local"][1], "_remote" => $paths["remote"][1]]);
308
            $this->getLogger()->info("OCR provider fail to download a file from the FTP server", ["_local" => $paths["local"][2], "_remote" => $paths["remote"][2]]);
309
        }
310
311
        return $result;
312
    }
313
314
    /**
315
     * Set the local directory "after".
316
     *
317
     * @param string $localDirectoryAfter The local directory "after".
318
     * @return OcrProvider Returns this OCR provider.
319
     */
320
    public function setLocalDirectoryAfter($localDirectoryAfter) {
321
        $this->localDirectoryAfter = $localDirectoryAfter;
322
        return $this;
323
    }
324
325
    /**
326
     * Set the local directory "before".
327
     *
328
     * @param string $localDirectoryBefore The local directory "before"
329
     * @return OcrProvider Returns this OCR provider.
330
     */
331
    public function setLocalDirectoryBefore($localDirectoryBefore) {
332
        $this->localDirectoryBefore = $localDirectoryBefore;
333
        return $this;
334
    }
335
336
    /**
337
     * Set the local directory "error".
338
     *
339
     * @param string $localDirectoryError The local directory "error".
340
     * @return OcrProvider Returns this OCR provider.
341
     */
342
    public function setLocalDirectoryError($localDirectoryError) {
343
        $this->localDirectoryError = $localDirectoryError;
344
        return $this;
345
    }
346
347
    /**
348
     * Set the remote directory "after".
349
     *
350
     * @param string $remoteDirectoryAfter The remote directory "after".
351
     * @return OcrProvider Returns this OCR provider.
352
     */
353
    public function setRemoteDirectoryAfter($remoteDirectoryAfter) {
354
        $this->remoteDirectoryAfter = $remoteDirectoryAfter;
355
        return $this;
356
    }
357
358
    /**
359
     * Set the remote directory "before".
360
     *
361
     * @param string $remoteDirectoryBefore The remote directory "before".
362
     * @return OcrProvider Returns this OCR provider.
363
     */
364
    public function setRemoteDirectoryBefore($remoteDirectoryBefore) {
365
        $this->remoteDirectoryBefore = $remoteDirectoryBefore;
366
        return $this;
367
    }
368
369
    /**
370
     * Set the remote directory "error".
371
     *
372
     * @param string $remoteDirectoryError The remote directory "error".
373
     * @return OcrProvider Returns this OCR provider.
374
     */
375
    public function setRemoteDirectoryError($remoteDirectoryError) {
376
        $this->remoteDirectoryError = $remoteDirectoryError;
377
        return $this;
378
    }
379
}