Completed
Push — develop ( 0e60d3...418abb )
by Abdelrahman
10:31
created

DefaultImporterHandler::handle()   B

Complexity

Conditions 4
Paths 2

Size

Total Lines 30
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 30
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 20
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cortex\Foundation\Importers;
6
7
use Exception;
8
use Maatwebsite\Excel\Files\ImportHandler;
9
use Maatwebsite\Excel\Collections\CellCollection;
10
11
class DefaultImporterHandler implements ImportHandler
12
{
13
    public function handle($importer)
14
    {
15
        $failed = collect();
16
        $created = collect();
17
        $updated = collect();
18
19
        $importer->each(function(CellCollection $row) use($importer, &$failed, &$created, &$updated) {
20
            $fillable = $row->intersectByKeys(array_flip(app($importer->config['resource'])->getFillable()))->toArray();
21
22
            try {
23
                $record = tap(app($importer->config['resource'])->firstOrNew($fillable), function ($instance) {
24
                    $instance->save();
25
                });
26
27
                $record->wasRecentlyCreated
28
                    ? $created->push($record->{$importer->config['name']})
29
                    : $updated->push($record->{$importer->config['name']});
30
            } catch (Exception $e) {
31
                $failed->push($record->{$importer->config['name']});
32
            }
33
        });
34
35
        ! $importer->config['log'] || activity()
36
            ->performedOn(app($importer->config['resource']))
37
            ->withProperties([
38
                    'count' => ['created' => $created->count(), 'updated' => $updated->count(), 'failed' => $failed->count()],
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 126 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
39
                    'names' => ['created' => $created, 'updated' => $updated, 'failed' => $failed]]
40
            )
41
            ->log('imported');
42
    }
43
}
44