|
1
|
|
|
<?php namespace JobApis\JobsToMail\Jobs\Notifications; |
|
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
|
|
|
'source', |
|
21
|
|
|
'datePosted', |
|
22
|
|
|
]; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @var string $id Notification ID |
|
26
|
|
|
*/ |
|
27
|
|
|
protected $id; |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* Create a new job instance. |
|
31
|
|
|
*/ |
|
32
|
1 |
|
public function __construct($id = null) |
|
33
|
|
|
{ |
|
34
|
1 |
|
$this->id = $id; |
|
35
|
1 |
|
} |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* Generate a CSV a single notification and return the file path |
|
39
|
|
|
* |
|
40
|
|
|
* @return string file path for download |
|
41
|
|
|
*/ |
|
42
|
1 |
|
public function handle( |
|
43
|
|
|
CustomDatabaseNotification $notifications, |
|
44
|
|
|
JobFilter $jobFilter, |
|
45
|
|
|
Writer $csv |
|
46
|
|
|
) { |
|
47
|
|
|
// Get the jobs from the Database |
|
48
|
1 |
|
$jobs = $notifications->where('id', $this->id)->first()->data; |
|
49
|
|
|
|
|
50
|
|
|
// Filter raw jobs array - Move to filter class |
|
51
|
1 |
|
$jobs = $jobFilter->filterFields($jobs, $this->csvHeaders); |
|
52
|
|
|
|
|
53
|
|
|
// Compose a CSV with all the jobs |
|
54
|
1 |
|
return $this->createCsv($csv, $jobs, $this->id.'.csv'); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
1 |
|
private function createCsv(Writer $csv, array $items = [], $filename = null) |
|
58
|
|
|
{ |
|
59
|
|
|
// Make sure line endings are detected. |
|
60
|
1 |
|
if (!ini_get("auto_detect_line_endings")) { |
|
61
|
1 |
|
ini_set("auto_detect_line_endings", '1'); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
// Set the path for the csv to save |
|
65
|
1 |
|
$path = storage_path('app/'.$filename); |
|
66
|
|
|
|
|
67
|
|
|
// Instantiate a new csv writer |
|
68
|
1 |
|
if (file_exists($path)) { |
|
69
|
|
|
$csv = $csv->createFromPath($path, 'rx+'); |
|
70
|
|
|
} else { |
|
71
|
1 |
|
$csv = $csv->createFromPath($path, 'x+'); |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
// Add header rows |
|
75
|
1 |
|
$csv->insertOne(array_keys($items[0])); |
|
76
|
|
|
|
|
77
|
|
|
// Add each item as a new line to the CSV |
|
78
|
1 |
|
$csv->insertAll($items); |
|
79
|
|
|
|
|
80
|
1 |
|
return $path; |
|
81
|
|
|
} |
|
82
|
|
|
} |
|
83
|
|
|
|