|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types = 1); |
|
3
|
|
|
|
|
4
|
|
|
namespace App\Services; |
|
5
|
|
|
|
|
6
|
|
|
use Illuminate\Filesystem\Filesystem; |
|
7
|
|
|
|
|
8
|
|
|
class ImportService |
|
9
|
|
|
{ |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* Validate files to import |
|
13
|
|
|
* |
|
14
|
|
|
* @param string|array $filePaths paths to text files to import |
|
15
|
|
|
* @return array validation errors |
|
16
|
|
|
* |
|
17
|
|
|
* @todo adapt validation error output in case of multiple file paths |
|
18
|
|
|
*/ |
|
19
|
|
|
public function validate($filePaths) : array |
|
20
|
|
|
{ |
|
21
|
|
|
|
|
22
|
|
|
if (is_array($filePaths) === false) { |
|
23
|
|
|
$filePaths = [$filePaths]; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
foreach ($filePaths as $filePath) { |
|
27
|
|
|
|
|
28
|
|
|
if (is_string($filePath) === false || |
|
29
|
|
|
file_exists($filePath) === false || |
|
|
|
|
|
|
30
|
|
|
is_readable($filePath) === false || |
|
|
|
|
|
|
31
|
|
|
is_file($filePath) === false |
|
|
|
|
|
|
32
|
|
|
) { |
|
33
|
|
|
return ["Invalid file path"]; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
$fileSystem = new Filesystem; |
|
37
|
|
|
$fileMimeType = $fileSystem->mimeType($filePath); |
|
|
|
|
|
|
38
|
|
|
if ($fileMimeType !== "text/plain") { |
|
39
|
|
|
return ["Invalid file type"]; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
if (file($filePath) === false || |
|
|
|
|
|
|
43
|
|
|
count(file($filePath)) === 0) { |
|
|
|
|
|
|
44
|
|
|
return ["Empty file"]; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
return []; |
|
50
|
|
|
|
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* Import files |
|
55
|
|
|
* |
|
56
|
|
|
* @param string|array $filePaths paths to text files to import |
|
57
|
|
|
* @param string $class class of models to import |
|
58
|
|
|
*/ |
|
59
|
|
|
public function import($filePaths, string $class) |
|
60
|
|
|
{ |
|
61
|
|
|
|
|
62
|
|
|
if (in_array("App\Models\Interfaces\Importable", class_implements($class)) === false) { |
|
63
|
|
|
throw new \InvalidArgumentException("Invalid import model class"); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
if (is_array($filePaths) === false) { |
|
67
|
|
|
$filePaths = [$filePaths]; |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
$records = file(implode(PHP_EOL, $filePaths)); |
|
|
|
|
|
|
71
|
|
|
|
|
72
|
|
|
// @todo add character check |
|
73
|
|
|
// @todo add uniqueness check |
|
74
|
|
|
// @todo add return of number of records imported |
|
75
|
|
|
|
|
76
|
|
|
// Data is cleaned. |
|
77
|
|
|
$records = array_unique(array_map("trim", $records)); |
|
|
|
|
|
|
78
|
|
|
|
|
79
|
|
|
foreach ($records as $record) { |
|
80
|
|
|
$model = new $class(); |
|
81
|
|
|
$model->name = $record; |
|
82
|
|
|
$model->save(); |
|
83
|
|
|
} |
|
84
|
|
|
|
|
85
|
|
|
} |
|
86
|
|
|
|
|
87
|
|
|
} |
|
88
|
|
|
|