-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwarranty_upload.php
76 lines (66 loc) · 1.87 KB
/
warranty_upload.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
class Warranty_upload
{
public function __construct()
{
# code...
}
public function handleUpload()
{
if( ! isset( $_FILES['csv']['tmp_name'])){
return;
}
$csv = $this->_convertFileToCsv($_FILES['csv']['tmp_name']);
$result = [
'csv_entries' => count($csv),
'updated' => 0,
'invalid' => 0,
];
foreach ($csv as $entry) {
if( ! $this->_validateEntry($entry)){
$result['invalid'] += 1;
}
else{
$result['updated'] += $this->_updateEntry($entry);
}
}
return $result;
}
private function _validateEntry($entry)
{
if( ! isset($entry['serial_number'])){
return false;
}
if( ! isset($entry['purchase_date'])){
return false;
}
if( ! isset($entry['end_date'])){
return false;
}
if( ! Reportdata_model::where('serial_number', $entry['serial_number'])->first()){
return false;
}
return true;
}
private function _updateEntry($entry)
{
$warranty = Warranty_model::firstOrNew(['serial_number' => $entry['serial_number']]);
$warranty->purchase_date = $entry['purchase_date'];
$warranty->end_date = $entry['end_date'];
$warranty->status = $entry['end_date'] >= date('Y-m-d') ? 'Supported' : 'Expired';
if($warranty->isDirty()){
$warranty->save();
return true;
}
return false;
}
private function _convertFileToCsv($file)
{
$csv = array_map('str_getcsv', file($file));
array_walk($csv, function(&$a) use ($csv) {
$a = array_combine($csv[0], $a);
});
array_shift($csv); # remove column header
return $csv;
}
}