Passed
Push — master ( 270226...e22eb7 )
by James
06:04 queued 11s
created

AutoImport::importFile()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
eloc 16
c 2
b 0
f 0
nc 5
nop 1
dl 0
loc 26
rs 9.7333
1
<?php
2
3
namespace App\Console\Commands;
4
5
use App\Console\HaveAccess;
6
use App\Console\StartImport;
7
use App\Console\VerifyJSON;
8
use Illuminate\Console\Command;
9
10
/**
11
 * Class AutoImport
12
 */
13
class AutoImport extends Command
14
{
15
    use HaveAccess, VerifyJSON, StartImport;
16
17
    /** @var array */
18
    private const IGNORE = ['.', '..'];
19
    /**
20
     * The console command description.
21
     *
22
     * @var string
23
     */
24
    protected $description = 'Will automatically import from the given directory and use the JSON and CSV files found.';
25
    /**
26
     * The name and signature of the console command.
27
     *
28
     * @var string
29
     */
30
    protected $signature = 'csv:auto-import {directory : The directory from which to import automatically.}';
31
    /** @var string */
32
    private $directory = './';
33
34
    /**
35
     * Create a new command instance.
36
     *
37
     * @return void
38
     */
39
    public function __construct()
40
    {
41
        parent::__construct();
42
    }
43
44
    /**
45
     * Execute the console command.
46
     *
47
     * @return int
48
     */
49
    public function handle(): int
50
    {
51
        $access = $this->haveAccess();
52
        if (false === $access) {
53
            $this->error('Could not connect to your local Firefly III instance.');
54
55
            return 1;
56
        }
57
58
        $this->directory = $this->argument('directory') ?? './';
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->argument('directory') ?? './' can also be of type string[]. However, the property $directory is declared as type string. 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
        $this->line(sprintf('Going to automatically import everything found in %s', $this->directory));
0 ignored issues
show
Bug introduced by
It seems like $this->directory can also be of type string[]; however, parameter $args of sprintf() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

59
        $this->line(sprintf('Going to automatically import everything found in %s', /** @scrutinizer ignore-type */ $this->directory));
Loading history...
60
61
        $files = $this->getFiles();
62
        if (0 === count($files)) {
63
            $this->info(sprintf('There are no files in directory %s', $this->directory));
64
            $this->info('To learn more about this process, read the docs:');
65
            $this->info('https://firefly-iii.gitbook.io/firefly-iii-csv-importer/installing-and-running/docker');
66
67
            return 1;
68
        }
69
        $this->line(sprintf('Found %d CSV + JSON file sets in %s', count($files), $this->directory));
70
71
        $this->importFiles($files);
72
73
        return 0;
74
    }
75
76
    /**
77
     * @param string $file
78
     *
79
     * @return string
80
     */
81
    private function getExtension(string $file): string
82
    {
83
        $parts = explode('.', $file);
84
        if (1 === count($parts)) {
85
            return '';
86
        }
87
88
        return $parts[count($parts) - 1];
89
    }
90
91
    /**
92
     * @return array
93
     */
94
    private function getFiles(): array
95
    {
96
        if (null === $this->directory || '' === $this->directory) {
97
            $this->error(sprintf('Directory "%s" is empty or invalid.', $this->directory));
98
99
            return [];
100
        }
101
        $files  = array_diff(scandir($this->directory), self::IGNORE);
0 ignored issues
show
Bug introduced by
It seems like scandir($this->directory) can also be of type false; however, parameter $array1 of array_diff() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

101
        $files  = array_diff(/** @scrutinizer ignore-type */ scandir($this->directory), self::IGNORE);
Loading history...
102
        $return = [];
103
        foreach ($files as $file) {
104
            if ('csv' === $this->getExtension($file) && $this->hasJsonConfiguration($file)) {
105
                $return[] = $file;
106
            }
107
        }
108
109
        return $return;
110
    }
111
112
    /**
113
     * @param string $file
114
     *
115
     * @return bool
116
     */
117
    private function hasJsonConfiguration(string $file): bool
118
    {
119
        $short    = substr($file, 0, -4);
120
        $jsonFile = sprintf('%s.json', $short);
121
        $fullJson = sprintf('%s/%s', $this->directory, $jsonFile);
122
        if (!file_exists($fullJson)) {
123
            $this->warn(sprintf('Can\'t find JSON file "%s" expected to go with CSV file "%s". CSV file will be ignored.', $fullJson, $file));
124
125
            return false;
126
        }
127
128
        return true;
129
    }
130
131
    /**
132
     * @param string $file
133
     */
134
    private function importFile(string $file): void
135
    {
136
        $csvFile  = sprintf('%s/%s', $this->directory, $file);
137
        $jsonFile = sprintf('%s/%s.json', $this->directory, substr($file, 0, -4));
138
139
        // do JSON check
140
        $jsonResult = $this->verifyJSON($jsonFile);
141
        if (false === $jsonResult) {
142
            $message = sprintf('The importer can\'t import %s: could not decode the JSON in config file %s.', $csvFile, $jsonFile);
143
            $this->error($message);
144
145
            return;
146
        }
147
        $configuration = json_decode(file_get_contents($jsonFile), true, 512, JSON_THROW_ON_ERROR);
148
        $this->line(sprintf('Going to import from file %s using configuration %s.', $csvFile, $jsonFile));
149
        // create importer
150
        $csv    = file_get_contents($csvFile);
151
        $result = $this->startImport($csv, $configuration);
152
        if (0 === $result) {
153
            $this->line('Import complete.');
154
        }
155
        if (0 !== $result) {
156
            $this->warn('The import finished with errors.');
157
        }
158
159
        $this->line(sprintf('Done importing from file %s using configuration %s.', $csvFile, $jsonFile));
160
    }
161
162
    /**
163
     * @param array $files
164
     */
165
    private function importFiles(array $files): void
166
    {
167
        /** @var string $file */
168
        foreach ($files as $file) {
169
            $this->importFile($file);
170
        }
171
    }
172
}
173