Completed
Pull Request — master (#25)
by Karl
05:00
created

GenerateCsv::createCsv()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 21
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 8
cts 8
cp 1
rs 9.3142
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 3
crap 2
1
<?php namespace JobApis\JobsToMail\Jobs\Collections;
2
3
use JobApis\JobsToMail\Filters\JobFilter;
4
use JobApis\JobsToMail\Models\CustomDatabaseNotification;
5
use League\Csv\Writer;
6
7
class GenerateCsv
8
{
9
    /**
10
     * @var array $csvHeaders
11
     */
12
    protected $csvHeaders = [
13
        'name',
14
        'description',
15
        'url',
16
        'company',
17
        'location',
18
        'query',
19
        'industry',
20
        'datePosted',
21
    ];
22
23
    /**
24
     * @var string $id Collection ID
25
     */
26
    protected $id;
27
28
    /**
29
     * Create a new job instance.
30
     */
31 1
    public function __construct($id = null)
32
    {
33 1
        $this->id = $id;
34 1
    }
35
36
    /**
37
     * Generate a CSV a single notification and return the file path
38
     *
39
     * @return string file path for download
40
     */
41 1
    public function handle(
42
        CustomDatabaseNotification $notifications,
43
        JobFilter $jobFilter,
44
        Writer $csv
45
    ) {
46
        // Get the jobs from the Database
47 1
        $jobs = $notifications->where('id', $this->id)->first()->data;
48
49
        // Filter raw jobs array - Move to filter class
50 1
        $jobs = $jobFilter->filterFields($jobs, $this->csvHeaders);
51
52
        // Compose a CSV with all the jobs
53 1
        return $this->createCsv($csv, $jobs, $this->id.'.csv');
54
    }
55
56 1
    private function createCsv(Writer $csv, array $items = [], $filename = null)
57
    {
58
        // Make sure line endings are detected.
59 1
        if (!ini_get("auto_detect_line_endings")) {
60 1
            ini_set("auto_detect_line_endings", '1');
61
        }
62
63
        // Set the path for the csv to save
64 1
        $path = storage_path('app/'.$filename);
65
66
        // Instantiate a new csv writer
67 1
        $csv = $csv->createFromPath($path, 'x+');
68
69
        // Add header rows
70 1
        $csv->insertOne(array_keys($items[0]));
71
72
        // Add each item as a new line to the CSV
73 1
        $csv->insertAll($items);
74
75 1
        return $path;
76
    }
77
}
78