Passed
Push — master ( 554f4f...40d218 )
by James
03:44 queued 16s
created

AutoImport::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
declare(strict_types=1);
3
/**
4
 * AutoImport.php
5
 * Copyright (c) 2020 [email protected]
6
 *
7
 * This file is part of the Firefly III CSV importer
8
 * (https://github.com/firefly-iii/csv-importer).
9
 *
10
 * This program is free software: you can redistribute it and/or modify
11
 * it under the terms of the GNU Affero General Public License as
12
 * published by the Free Software Foundation, either version 3 of the
13
 * License, or (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU Affero General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Affero General Public License
21
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
22
 */
23
24
namespace App\Console\Commands;
25
26
use App\Console\HaveAccess;
27
use App\Console\StartImport;
28
use App\Console\VerifyJSON;
29
use Illuminate\Console\Command;
30
31
/**
32
 * Class AutoImport
33
 */
34
class AutoImport extends Command
35
{
36
    use HaveAccess, VerifyJSON, StartImport;
37
38
    /** @var array */
39
    private const IGNORE = ['.', '..'];
40
    /**
41
     * The console command description.
42
     *
43
     * @var string
44
     */
45
    protected $description = 'Will automatically import from the given directory and use the JSON and CSV files found.';
46
    /**
47
     * The name and signature of the console command.
48
     *
49
     * @var string
50
     */
51
    protected $signature = 'csv:auto-import {directory : The directory from which to import automatically.}';
52
    /** @var string */
53
    private $directory = './';
54
55
    /**
56
     * Execute the console command.
57
     *
58
     * @return int
59
     */
60
    public function handle(): int
61
    {
62
        $access = $this->haveAccess();
63
        if (false === $access) {
64
            $this->error('Could not connect to your local Firefly III instance.');
65
66
            return 1;
67
        }
68
69
        $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...
70
        $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

70
        $this->line(sprintf('Going to automatically import everything found in %s', /** @scrutinizer ignore-type */ $this->directory));
Loading history...
71
72
        $files = $this->getFiles();
73
        if (0 === count($files)) {
74
            $this->info(sprintf('There are no files in directory %s', $this->directory));
75
            $this->info('To learn more about this process, read the docs:');
76
            $this->info('https://firefly-iii.gitbook.io/firefly-iii-csv-importer/installing-and-running/docker');
77
78
            return 1;
79
        }
80
        $this->line(sprintf('Found %d CSV + JSON file sets in %s', count($files), $this->directory));
81
82
        $this->importFiles($files);
83
84
        return 0;
85
    }
86
87
    /**
88
     * @param string $file
89
     *
90
     * @return string
91
     */
92
    private function getExtension(string $file): string
93
    {
94
        $parts = explode('.', $file);
95
        if (1 === count($parts)) {
96
            return '';
97
        }
98
99
        return $parts[count($parts) - 1];
100
    }
101
102
    /**
103
     * @return array
104
     */
105
    private function getFiles(): array
106
    {
107
        if (null === $this->directory || '' === $this->directory) {
108
            $this->error(sprintf('Directory "%s" is empty or invalid.', $this->directory));
109
110
            return [];
111
        }
112
        $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

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