Completed
Push — master ( d191f9...11a393 )
by Tyler
02:21
created

PeopleMatter::getPerson()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3.0052

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 11
cts 12
cp 0.9167
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 10
nc 3
nop 1
crap 3.0052
1
<?php
2
3
namespace Zenapply\PeopleMatter;
4
5
use Exception;
6
use DateTime;
7
use GuzzleHttp\Client;
8
use Zenapply\PeopleMatter\Exceptions\PeopleMatterException;
9
10
class PeopleMatter
11
{
12
    protected $alias;
13
    protected $authenticated = false;
14
    protected $client;
15
    protected $host;
16
    protected $password;
17
    protected $username;
18
19
    /**
20
     * Creates a PeopleMatter instance that can register and unregister webhooks with the API
21
     * @param string      $username The Username
22
     * @param string      $password The Password
23
     * @param string      $alias    The business alias
24
     * @param string      $host     The host to connect to
25
     * @param Client|null $client   The Guzzle client (used for testing)
26
     */
27 15
    public function __construct($username, $password, $alias, $host = "api.peoplematter.com", Client $client = null)
28
    {
29 15
        $this->alias = $alias;
30 15
        $this->client = $client;
31 15
        $this->host = $host;
32 15
        $this->password = $password;
33 15
        $this->username = $username;
34 15
    }
35
36 3
    public function hire(Person $person, Job $job, BusinessUnit $businessUnit, $timeStatus, DateTime $hired_at = null)
37
    {
38 3
        $this->login();
39
40 3
        if ($hired_at === null) {
41
            $hired_at = new DateTime('now');
42
        }
43
44 3
        if (!in_array($timeStatus, ["FullTime", "PartTime"])) {
45
            throw new Exception("{$timeStatus} is invalid! Please use FullTime or PartTime");
46
        }
47
48 3
        $url = "https://{$this->host}/api/services/platform/hireemployee";
49
50 3
        return $this->request('POST', $url, [
51 3
            'debug' => true,
52
            'json' => [
53 3
                "HireDate" => $hired_at->format("m/d/Y"),
54
                "Business" => [
55
                    "Alias" => "cafezupassandbox"
56 3
                ],
57
                "BusinessUnit" => [
58 3
                    "UnitNumber" => $businessUnit->UnitNumber
0 ignored issues
show
Bug introduced by
The property UnitNumber does not seem to exist in Zenapply\PeopleMatter\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...
59 3
                ],
60 3
                "Person" => $person->toArray(),
61
                "JobPositions" => [
62
                    [
63
                        "Business" => [
64
                            "Alias" => "cafezupassandbox"
65 3
                        ],
66
                        "BusinessUnit" => [
67 3
                            "UnitNumber" => $businessUnit->UnitNumber
68 3
                        ],
69
                        "Job" => [
70 3
                            "Code" => $job->Code,
0 ignored issues
show
Bug introduced by
The property Code does not seem to exist in Zenapply\PeopleMatter\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...
71 3
                        ],
72 3
                        "TimeStatus" => $timeStatus,
73 3
                        "Person" => $person->toArray(),
74
                    ]
75 3
                ]
76 3
            ]
77 3
        ]);
78
    }
79
80 6
    protected function buildUrl($resource)
81
    {
82 6
        return "https://{$this->host}/api/{$resource}";
83
    }
84
85 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...
86
    {
87 3
        $this->login();
88 3
        $response = $this->request('GET', $this->buildUrl("businessunit?businessalias={$this->alias}"));
89
90 3
        $units = [];
91 3
        foreach ($response["Records"] as $unit) {
92 3
            $units[] = new BusinessUnit($unit);
93 3
        }
94
95 3
        return $units;
96
    }
97
98 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...
99
    {
100 3
        $this->login();
101 3
        $response = $this->request('GET', $this->buildUrl("job?businessalias={$this->alias}"));
102
103 3
        $jobs = [];
104 3
        foreach ($response["Jobs"] as $unit) {
105 3
            $jobs[] = new Job($unit);
106 3
        }
107
108 3
        return $jobs;
109
    }
110
111 3
    public function getPerson($email)
112
    {
113 3
        if (empty($email)) {
114
            throw new Exception("Email is invalid!");
115
        }
116 3
        $this->login();
117 3
        $units = [];
118 3
        $url = "https://{$this->host}/api/businessunitemployee?businessalias={$this->alias}&PersonEmailAddress={$email}";
119 3
        $response = $this->request('GET', $url);
120
121 3
        foreach ($response["Records"] as $unit) {
122 3
            $units[] = new Person($unit);
123 3
        }
124
125 3
        return $units;
126 2
    }
127
128 12
    protected function login()
129
    {
130 12
        if ($this->authenticated !== true) {
131 12
            $url = "https://{$this->host}/api/account/login";
132 12
            $this->request('POST', $url, [
133
                'form_params' => [
134 12
                    'email' => $this->username,
135 12
                    'password' => $this->password,
136
                ]
137 12
            ]);
138 12
            $this->authenticated = true;
139 12
        }
140
141 12
        return $this->authenticated;
142
    }
143
144
    /**
145
     * Returns the Client instance
146
     * @return Client
147
     */
148 12
    public function getClient()
149
    {
150 12
        if (!$this->client instanceof Client) {
151
            $this->client = new Client([
152
                'cookies' => true
153
            ]);
154
        }
155 12
        return $this->client;
156
    }
157
    
158
    /**
159
     * Executes a request to the PeopleMatter API
160
     * @param  string $method  The request type
161
     * @param  string $url     The url to request
162
     * @param  array  $options An array of options for the request
163
     * @return array           The response as an array
164
     */
165 12
    protected function request($method, $url, $options = [])
166
    {
167 12
        $client = $this->getClient();
168
        try {
169 12
            $response = $client->request($method, $url, $options);
170 12
        } catch (\GuzzleHttp\Exception\ClientException $e) {
171 3
            $response = $e->getResponse();
172 3
            throw new PeopleMatterException($response->getStatusCode().": ".$response->getReasonPhrase(), 1);
173
        }
174
175 12
        $json = json_decode($response->getBody(), true);
176
177 12
        if (!empty($json["ErrorMessage"])) {
178
            throw new PeopleMatterException($json["ErrorMessage"], $json["ErrorCode"]);
179
        }
180
181 12
        return $json;
182
    }
183
}
184