Completed
Push — master ( cab24a...fa205f )
by Tyler
03:00
created

PeopleMatter::getEmployee()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 3

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 20
ccs 14
cts 14
cp 1
rs 9.4285
cc 3
eloc 12
nc 3
nop 1
crap 3
1
<?php
2
3
namespace Zenapply\PeopleMatter;
4
5
use DateTime;
6
use Exception;
7
use GuzzleHttp\Client;
8
use Zenapply\PeopleMatter\Exceptions\PeopleMatterException;
9
use Zenapply\PeopleMatter\Models\BusinessUnit;
10
use Zenapply\PeopleMatter\Models\Job;
11
use Zenapply\PeopleMatter\Models\Person;
12
use Zenapply\PeopleMatter\Models\Employee;
13
14
class PeopleMatter
15
{
16
    protected $alias;
17
    protected $authenticated = false;
18
    protected $client;
19
    protected $host;
20
    protected $password;
21
    protected $username;
22
23
    /**
24
     * Creates a PeopleMatter instance that can register and unregister webhooks with the API
25
     * @param string      $username The Username
26
     * @param string      $password The Password
27
     * @param string      $alias    The business alias
28
     * @param string      $host     The host to connect to
29
     * @param Client|null $client   The Guzzle client (used for testing)
30
     */
31 15
    public function __construct($username, $password, $alias, $host = "api.peoplematter.com", Client $client = null)
32
    {
33 15
        $this->alias = $alias;
34 15
        $this->client = $client;
35 15
        $this->host = $host;
36 15
        $this->password = $password;
37 15
        $this->username = $username;
38 15
    }
39
40 3
    public function hire(Person $person, Job $job, BusinessUnit $businessUnit, $timeStatus, DateTime $hired_at = null)
41
    {
42 3
        $this->login();
43
44 3
        if ($hired_at === null) {
45
            $hired_at = new DateTime("now");
46
        }
47
48 3
        if (!in_array($timeStatus, ["FullTime", "PartTime"])) {
49
            throw new Exception("{$timeStatus} is invalid! Please use FullTime or PartTime");
50
        }
51
52 3
        $url = "https://{$this->host}/api/services/platform/hireemployee";
53
54 3
        return $this->request("POST", $url, [
55
            "json" => [
56 3
                "HireDate" => $hired_at->format("m/d/Y"),
57
                "Business" => [
58 3
                    "Alias" => $this->alias,
59 3
                ],
60
                "BusinessUnit" => [
61 3
                    "UnitNumber" => $businessUnit->UnitNumber
0 ignored issues
show
Bug introduced by
The property UnitNumber does not seem to exist in Zenapply\PeopleMatter\Models\BusinessUnit.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
62 3
                ],
63 3
                "Person" => $person->toArray(),
64
                "JobPositions" => [
65
                    [
66
                        "Business" => [
67 3
                            "Alias" => $this->alias,
68 3
                        ],
69
                        "BusinessUnit" => [
70 3
                            "UnitNumber" => $businessUnit->UnitNumber
71 3
                        ],
72
                        "Job" => [
73 3
                            "Code" => $job->Code,
0 ignored issues
show
Bug introduced by
The property Code does not seem to exist in Zenapply\PeopleMatter\Models\Job.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
74 3
                        ],
75 3
                        "TimeStatus" => $timeStatus,
76 3
                        "Person" => $person->toArray(),
77
                    ]
78 3
                ]
79 3
            ]
80 3
        ]);
81
    }
82
83
    /**
84
     * @return string
85
     */
86 9
    protected function buildUrl($resource)
87
    {
88 9
        return "https://{$this->host}/api/{$resource}";
89
    }
90
91 3 View Code Duplication
    public function getBusinessUnits()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
92
    {
93 3
        $this->login();
94 3
        $response = $this->request("GET", $this->buildUrl("businessunit"), [
95
            "query" => [
96 3
                "businessalias" => $this->alias,
97
            ]
98 3
        ]);
99
100 3
        $units = [];
101 3
        foreach ($response["Records"] as $unit) {
102 3
            $units[] = new BusinessUnit($unit);
103 3
        }
104
105 3
        return $units;
106
    }
107
108 3 View Code Duplication
    public function getJobs()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
109
    {
110 3
        $this->login();
111 3
        $response = $this->request("GET", $this->buildUrl("job"), [
112
            "query" => [
113 3
                "businessalias" => $this->alias,
114
            ]
115 3
        ]);
116
117 3
        $jobs = [];
118 3
        foreach ($response["Jobs"] as $unit) {
119 3
            $jobs[] = new Job($unit);
120 3
        }
121
122 3
        return $jobs;
123
    }
124
125 3
    public function getEmployee($email)
126 1
    {
127 3
        if (empty($email)) {
128 2
            throw new Exception("Email is invalid!");
129
        }
130 3
        $this->login();
131 3
        $units = [];
132 3
        $response = $this->request("GET", $this->buildUrl("businessunitemployee"), [
133
            "query" => [
134 3
                "businessalias" => $this->alias,
135 3
                "PersonEmailAddress" => $email,
136
            ]
137 3
        ]);
138
139 3
        foreach ($response["Records"] as $unit) {
140 3
            $units[] = new Employee($unit);
141 3
        }
142
143 3
        return $units;
144
    }
145
146
147 12
    protected function login()
148
    {
149 12
        if ($this->authenticated !== true) {
150 12
            $url = "https://{$this->host}/api/account/login";
151 12
            $this->request("POST", $url, [
152
                "form_params" => [
153 12
                    "email" => $this->username,
154 12
                    "password" => $this->password,
155
                ]
156 12
            ]);
157 12
            $this->authenticated = true;
158 12
        }
159
160 12
        return $this->authenticated;
161
    }
162
163
    /**
164
     * Returns the Client instance
165
     * @return Client
166
     */
167 12
    public function getClient()
168
    {
169 12
        if (!$this->client instanceof Client) {
170
            $this->client = new Client([
171
                "cookies" => true
172
            ]);
173
        }
174 12
        return $this->client;
175
    }
176
    
177
    /**
178
     * Executes a request to the PeopleMatter API
179
     * @param  string $method  The request type
180
     * @param  string $url     The url to request
181
     * @param  array  $options An array of options for the request
182
     * @return array           The response as an array
183
     */
184 12
    protected function request($method, $url, $options = [])
185
    {
186 12
        $client = $this->getClient();
187
        try {
188 12
            $response = $client->request($method, $url, $options);
189 12
        } catch (\GuzzleHttp\Exception\ClientException $e) {
190
            $response = $e->getResponse();
191
            throw new PeopleMatterException($response->getStatusCode().": ".$response->getReasonPhrase(), 1);
192
        }
193
194 12
        $body = $response->getBody();
195 12
        if (!is_array($body)) {
196 12
            $json = json_decode($body, true);
197 12
        } else {
198
            $json = $body;
199
        }
200
201 12
        if (!empty($json["ErrorMessage"])) {
202
            throw new PeopleMatterException($json["ErrorMessage"], $json["ErrorCode"]);
203
        }
204
205 12
        return $json;
206
    }
207
}
208