Completed
Pull Request — master (#6)
by Shawn
03:12
created

JpasImportHandler::getCorrectDateFormat()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.0534
c 0
b 0
f 0
cc 4
eloc 9
nc 4
nop 1
1
<?php
2
3
namespace SET\Handlers\Excel;
4
5
use Illuminate\Support\Collection;
6
use Illuminate\Support\Facades\Input;
7
use Maatwebsite\Excel\Files\ImportHandler;
8
use SET\User;
9
10
/**
11
 * Class JpasImportHandler.
12
 *
13
 * Going to handle importing our JPAS excel file.
14
 */
15
class JpasImportHandler implements ImportHandler
16
{
17
    private $unique;
18
    private $changes;
19
20
    /**
21
     * Set our variables as new collections.
22
     */
23
    public function __construct()
24
    {
25
        $this->unique = new Collection();
26
        $this->changes = new Collection();
27
    }
28
29
    /**
30
     * Initial call from UserController.
31
     * Based on what we get, we will either call an initial import or the resolve import.
32
     *
33
     * @param $import
34
     *
35
     * @return array
36
     */
37
    public function handle($import)
38
    {
39
        $excel = $import->get();
40
        $data = Input::all();
41
42
        //We always pass a token and the file. If there is anything more, then we are resolving.
43
        if ($data['resolveImport']) {
44
            $this->resolveImport($excel, $data);
45
        } else {
46
            $this->initialImport($excel);
47
        }
48
49
        //Return this data. It is just used for the initial import, but still nice to see.
50
        return ['unique' => $this->unique, 'changes' => $this->changes];
51
    }
52
53
    /**
54
     * Cycle through our excel spreadsheet.
55
     * If we can't figure where data goes, we will push it to a collection so the user can map it.
56
     * Otherwise, we will update the record.
57
     *
58
     * @param $excel
59
     */
60
    private function initialImport($excel)
61
    {
62
        foreach ($excel as $row) {
63
            $row->name = preg_replace('/(,\s|\s)/', '_', $row->name);
64
            if (!is_null($row->name) && $row->name != '') { //we get a bunch of null records that we can ignore.
65
                $user = User::where('jpas_name', $row->name)->first(); //see if the record maps to a user
66
                if (is_null($user)) {
67
                    $this->unique->push($row); //if no results, we need to have the admin map this record to a user.
68
                } else {
69
                    $this->getUserChanges($this->mapJpasToUser($user, $row));
70
                }
71
            }
72
        }
73
    }
74
75
    /**
76
     * User has mapped some accounts. We need to update those records.
77
     *
78
     * @param $excel
79
     * @param $data
80
     */
81
    private function resolveImport($excel, $data)
82
    {
83
        foreach ($data as $jpasName => $userGroup) {
84
            if ($jpasName == 'approve') {
85
                $this->updateUserData($userGroup);
86
            } elseif ($userGroup != '' && is_numeric($userGroup)) {
87
                $this->importNewData($excel, $userGroup, $jpasName);
88
            }
89
        }
90
    }
91
92
    /**
93
     * Place changes so the user can approve/reject them.
94
     *
95
     * @param $user
96
     */
97
    private function getUserChanges($user)
98
    {
99
        if ($user->isDirty()) {
100
            foreach ($user->getDirty() as $attribute => $newValue) {
101
                $this->changes->push([
102
                    'user'     => $user,
103
                    'field'    => $attribute,
104
                    'original' => $user->getOriginal($attribute),
105
                    'new'      => $newValue,
106
                ]);
107
            }
108
        }
109
    }
110
111
    /**
112
     * Update user. If there are changes, let's log them to an array.
113
     *
114
     * @param $user
115
     */
116
    private function updateAndLogUser($user)
117
    {
118
        //We will let the user know what changes were made.
119
        if ($user->isDirty()) {
120
            $log = "The following changes have been made for $user->userFullName: \n";
121
            foreach ($user->getDirty() as $attribute => $value) {
122
                $original = $user->getOriginal($attribute);
123
                $log .= "Changed $attribute from '$original' to '$value'.\n";
124
            }
125
            $user->save();
126
            $this->changes->push($log);
127
        }
128
    }
129
130
    /**
131
     * Map the data from our JPAS Excel to our User model.
132
     *
133
     * @param $user
134
     * @param $data
135
     */
136
    private function mapJpasToUser($user, $data)
137
    {
138
        $user->jpas_name = $data->name;
139
        $user->clearance = $data->eligibility;
140
        $user->elig_date = $this->getCorrectDateFormat($data->eligibility_date);
141
        $user->inv = $data->inves;
142
        $user->inv_close = $this->getCorrectDateFormat($data->prev_inves);
143
144
        return $user;
145
    }
146
147
    private function getCorrectDateFormat($date)
148
    {
149
        //If we get a date object, just format to Y-m-d
150
        if (is_object($date)) {
151
            return $date->toDateString();
152
        }
153
154
        //If we get a string in the a format such as 2/15/2015 0:00 then convert it to Y-m-d
155
        $d = \DateTime::createFromFormat('n/j/Y G:i', $date);
156
        if ($d) {
157
            return $d->format('Y-m-d');
158
        }
159
160
        //if already in Y-m-d, then just return it.
161
        $d = \DateTime::createFromFormat('Y-m-d', $date);
162
        if ($d) {
163
            return $date;
164
        }
165
166
        //Otherwise store null for the date.
167
    }
168
169
    /**
170
     * @param $excel
171
     * @param $userGroup
172
     * @param $jpasName
173
     *
174
     * @return mixed
175
     */
176
    private function importNewData($excel, $userGroup, $jpasName)
177
    {
178
        $user = User::find($userGroup);
179
        foreach ($excel as $row) {
180
            $row->name = preg_replace('/(,\s|\s)/', '_', $row->name);
181
            if ($row->name == $jpasName) {
182
                $this->updateAndLogUser($this->mapJpasToUser($user, $row));
183
            }
184
        }
185
    }
186
187
    /**
188
     * @param $userGroup
189
     */
190
    private function updateUserData($userGroup)
191
    {
192
        foreach ($userGroup as $userId => $changesGroup) {
193
            $user = User::find($userId);
194
            foreach ($changesGroup as $field => $newValue) {
195
                if ($newValue != '0') {
196
                    $user[$field] = $newValue;
197
                }
198
            }
199
            $this->updateAndLogUser($user);
200
        }
201
    }
202
}
203