Completed
Pull Request — master (#34)
by Romain
02:42
created

User::getInstance()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 2
crap 2
1
<?php
2
namespace Kerox\Messenger\Api;
3
4
use GuzzleHttp\ClientInterface;
5
use Kerox\Messenger\Request\UserRequest;
6
use Kerox\Messenger\Response\UserResponse;
7
use Kerox\Messenger\UserInterface;
8
9
class User extends AbstractApi implements UserInterface
10
{
11
12
    /**
13
     * @var null|\Kerox\Messenger\Api\User
14
     */
15
    private static $_instance;
16
17
    /**
18
     * Send constructor.
19
     *
20
     * @param string $pageToken
21
     * @param \GuzzleHttp\ClientInterface $client
22
     */
23 3
    public function __construct(string $pageToken, ClientInterface $client)
24
    {
25 3
        parent::__construct($pageToken, $client);
26 3
    }
27
28
    /**
29
     * @param string $pageToken
30
     * @param \GuzzleHttp\ClientInterface $client
31
     * @return \Kerox\Messenger\Api\User
32
     */
33 1
    public static function getInstance(string $pageToken, ClientInterface $client): User
34
    {
35 1
        if (self::$_instance === null) {
36 1
            self::$_instance = new User($pageToken, $client);
37
        }
38
39 1
        return self::$_instance;
40
    }
41
42
    /**
43
     * @param string $userId
44
     * @param array|null $fields
45
     * @return \Kerox\Messenger\Response\UserResponse
46
     */
47 2
    public function getProfile(string $userId, array $fields = null): UserResponse
48
    {
49 2
        $allowedFields = $this->getAllowedFields();
50 2
        if ($fields !== null) {
51 1
            foreach ($fields as $field) {
52 1
                if (!in_array($field, $allowedFields)) {
53 1
                    throw new \InvalidArgumentException($field . ' is not a valid value. $fields must only contain ' . implode(', ', $allowedFields));
54
                }
55
            }
56
        } else {
57 1
            $fields = $allowedFields;
58
        }
59
60 1
        $request = new UserRequest($this->pageToken, $fields);
61 1
        $response = $this->client->get(sprintf('%s', $userId), $request->build());
62
63 1
        return new UserResponse($response);
64
    }
65
66
    /**
67
     * @return array
68
     */
69 2
    private function getAllowedFields(): array
70
    {
71
        return [
72 2
            UserInterface::FIRST_NAME,
73 2
            UserInterface::LAST_NAME,
74 2
            UserInterface::PROFILE_PIC,
75 2
            UserInterface::LOCALE,
76 2
            UserInterface::TIMEZONE,
77 2
            UserInterface::GENDER,
78 2
            UserInterface::IS_PAYMENT_ENABLED,
79
        ];
80
    }
81
}
82