Passed
Branch real-time-api (954386)
by James
06:12
created

AbstractService   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 165
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 14
eloc 44
dl 0
loc 165
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A handle() 0 21 6
A log() 0 3 1
A dateTimeToMilliseconds() 0 3 1
A getStatus() 0 8 1
A __construct() 0 15 2
A arrayToList() 0 3 1
A getResponse() 0 8 2
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: james
5
 * Date: 19/07/2018
6
 * Time: 12:17
7
 */
8
9
namespace CwsOps\LivePerson\Services;
10
11
use CwsOps\LivePerson\Account\Config;
12
use CwsOps\LivePerson\Rest\Request;
13
use CwsOps\LivePerson\Rest\UrlBuilder;
14
use CwsOps\LivePerson\Traits\HasLoggerTrait;
15
use Psr\Log\LoggerInterface;
16
use Psr\Log\LogLevel;
17
18
/**
19
 * Class AbstractService
20
 *
21
 * @package CwsOps\LivePerson\Services
22
 */
23
abstract class AbstractService
24
{
25
    use HasLoggerTrait;
26
27
    const REQUEST_TYPE_V1 = 1;
28
    const REQUEST_TYPE_V2 = 2;
29
30
    const GLUE_CHAR = ',';
31
32
    /** @var UrlBuilder */
33
    protected $urlBuilder;
34
    /** @var Config */
35
    protected $config;
36
    /** @var LoggerInterface */
37
    private $logger;
38
    /** @var int */
39
    private $retryLimit;
40
    /** @var Request */
41
    protected $request;
42
    /** @var bool $responseSent */
43
    private $responseSent;
44
    /** @var \stdClass */
45
    protected $response;
46
47
    /**
48
     * AbstractService constructor.
49
     *
50
     * @param Config $config
51
     * @param int $retryLimit
52
     * @param LoggerInterface|null $logger
53
     */
54
    public function __construct(Config $config, int $retryLimit = 3, LoggerInterface $logger = null)
55
    {
56
        if ($retryLimit > 5) {
57
            throw new \InvalidArgumentException(
58
                sprintf('Maximum $retryLimit is 5 you tried setting %d, try setting a value between 0 and 5',
59
                    $retryLimit)
60
            );
61
        }
62
63
64
        $this->config = $config;
65
        $this->retryLimit = $retryLimit;
66
        $this->logger = $this->hasLogger($logger);
67
68
        $this->request = new Request($config, $retryLimit, $logger);
69
    }
70
71
72
    /**
73
     * @codeCoverageIgnore
74
     * Gets the current status of the account api.
75
     * @return array|\stdClass
76
     */
77
    public function getStatus()
78
    {
79
        // @codeCoverageIgnore
80
        $url = "https://status.liveperson.com/json?site={$this->config->getAccountId()}";
81
82
        $response = $this->request->v1($url, Request::METHOD_GET);
83
84
        return $response;
85
    }
86
87
    /**
88
     * Gets the response.
89
     *
90
     * @return \stdClass
91
     *
92
     * @throws RequestNotSentException
93
     */
94
    public function getResponse()
95
    {
96
        if (!$this->responseSent) {
97
            throw new RequestNotSentException();
98
        }
99
100
101
        return $this->response; //@codeCoverageIgnore
102
    }
103
104
    /**
105
     * Should provide the Live person domain id, this service will query against
106
     *
107
     * @return string
108
     */
109
    abstract protected function getDomain(): string;
110
111
    /**
112
     * Should provide the Live Person service the service will query against.
113
     *
114
     * @return string
115
     */
116
    abstract protected function getService(): string;
117
118
119
    /**
120
     * @codeCoverageIgnore
121
     * Handles the request and sets the response property.
122
     *
123
     * @param array $data Any data to pass in the request
124
     * @param string $method the HTTP request type.
125
     * @param int $type what type of request to make.
126
     *
127
     */
128
    protected function handle($data = [], $method = Request::METHOD_GET, $type = AbstractService::REQUEST_TYPE_V1)
129
    {
130
        // Check if the URL was built.
131
        if (!$this->urlBuilder->isUrlBuilt()) {
132
            $this->urlBuilder->build();
133
            $this->logger->debug("The URL was not built when trying to handle the request");
134
        }
135
136
        if ($type === self::REQUEST_TYPE_V1) {
137
            try {
138
                $this->response = $this->request->v1($this->urlBuilder->getUrl(), $method, $data);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->request->v1($this...tUrl(), $method, $data) can also be of type array. However, the property $response is declared as type stdClass. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
139
                $this->responseSent = true;
140
            } catch (\Exception $exception) {
141
                $this->logger->error("An exception occurred while the request took place: %s", $exception->getMessage());
0 ignored issues
show
Bug introduced by
$exception->getMessage() of type string is incompatible with the type array expected by parameter $context of Psr\Log\LoggerInterface::error(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

141
                $this->logger->error("An exception occurred while the request took place: %s", /** @scrutinizer ignore-type */ $exception->getMessage());
Loading history...
142
            }
143
        } elseif ($type === self::REQUEST_TYPE_V2) {
144
            try {
145
                $this->response = $this->request->v2($this->urlBuilder->getUrl(), $method, $data);
146
                $this->responseSent = true;
147
            } catch (\Exception $exception) {
148
                $this->logger->error("An exception occurred while the request took place: %s", $exception->getMessage());
149
            }
150
        }
151
    }
152
153
    /**
154
     * Converts a datetime obj into a int represents milliseconds since the epoc.
155
     *
156
     * @param \DateTime $dateTime
157
     *
158
     * @return int
159
     */
160
    protected function dateTimeToMilliseconds(\DateTime $dateTime)
161
    {
162
        return strtotime($dateTime->format('Y-m-d H:i:sP'));
163
    }
164
165
    /**
166
     * Converts a array to a string separated by a glue character.
167
     *
168
     * @param array $list the array to separate.
169
     * @param string $glueChar the character to glue the values together with.
170
     *
171
     * @return string the generated string.
172
     */
173
    protected function arrayToList(array $list, $glueChar = AbstractService::GLUE_CHAR)
174
    {
175
        return rtrim(implode($glueChar, $list), $glueChar);
176
    }
177
178
    /**
179
     * Logs an entry to the logger.
180
     *
181
     * @param string $message the message to log.
182
     * @param string $logLevel the level to log at.
183
     * @param array $context any additional context.
184
     */
185
    protected function log(string $message, string $logLevel = LogLevel::DEBUG, array $context = [])
186
    {
187
        $this->logger->log($logLevel, $message, $context);
188
    }
189
}
190