Issues (14)

src/Services/AbstractService.php (1 issue)

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
    public $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
     * @return Request
73
     */
74
    public function getRequest()
75
    {
76
        return $this->request;
77
    }
78
79
80
    /**
81
     * @codeCoverageIgnore
82
     * Gets the current status of the account api.
83
     * @return array|\stdClass
84
     */
85
    public function getStatus()
86
    {
87
        // @codeCoverageIgnore
88
        $url = "https://status.liveperson.com/json?site={$this->config->getAccountId()}";
89
90
        $response = $this->request->v1($url, Request::METHOD_GET);
91
92
        return $response;
93
    }
94
95
    /**
96
     * Gets the response.
97
     *
98
     * @return \stdClass
99
     *
100
     * @throws RequestNotSentException
101
     */
102
    public function getResponse()
103
    {
104
        if (!$this->responseSent) {
105
            throw new RequestNotSentException();
106
        }
107
108
109
        return $this->response; //@codeCoverageIgnore
110
    }
111
112
    /**
113
     * Should provide the Live person domain id, this service will query against
114
     *
115
     * @return string
116
     */
117
    abstract protected function getDomain(): string;
118
119
    /**
120
     * Should provide the Live Person service the service will query against.
121
     *
122
     * @return string
123
     */
124
    abstract protected function getService(): string;
125
126
127
    /**
128
     * @codeCoverageIgnore
129
     * Handles the request and sets the response property.
130
     *
131
     * @param array $data Any data to pass in the request
132
     * @param string $method the HTTP request type.
133
     * @param int $type what type of request to make.
134
     *
135
     */
136
    protected function handle($data = [], $method = Request::METHOD_GET, $type = AbstractService::REQUEST_TYPE_V1)
137
    {
138
        // Check if the URL was built.
139
        if (!$this->urlBuilder->isUrlBuilt()) {
140
            $this->urlBuilder->build();
141
            $this->logger->debug("The URL was not built when trying to handle the request");
142
        }
143
144
        if ($type === self::REQUEST_TYPE_V1) {
145
            try {
146
                $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...
147
                $this->responseSent = true;
148
            } catch (\Exception $exception) {
149
                $this->logger->error("An exception occurred while the request took place: %s", $exception->getTrace());
150
            }
151
        } elseif ($type === self::REQUEST_TYPE_V2) {
152
            try {
153
                $this->response = $this->request->v2($this->urlBuilder->getUrl(), $method, $data);
154
                $this->responseSent = true;
155
            } catch (\Exception $exception) {
156
                $this->logger->error("An exception occurred while the request took place: %s", $exception->getTrace());
157
            }
158
        }
159
    }
160
161
    /**
162
     * @codeCoverageIgnore
163
     *
164
     * Converts a datetime obj into a int represents milliseconds since the epoc.
165
     *
166
     * @param \DateTime $dateTime
167
     *
168
     * @return int
169
     */
170
    protected function dateTimeToMilliseconds(\DateTime $dateTime)
171
    {
172
        return strtotime($dateTime->format('Y-m-d H:i:sP'));
173
    }
174
175
    /**
176
     * @codeCoverageIgnore
177
     * Converts a array to a string separated by a glue character.
178
     *
179
     * @param array $list the array to separate.
180
     * @param string $glueChar the character to glue the values together with.
181
     *
182
     * @return string the generated string.
183
     */
184
    protected function arrayToList(array $list, $glueChar = AbstractService::GLUE_CHAR)
185
    {
186
        return rtrim(implode($glueChar, $list), $glueChar);
187
    }
188
189
    /**
190
     * @codeCoverageIgnore
191
     * Logs an entry to the logger.
192
     *
193
     * @param string $message the message to log.
194
     * @param string $logLevel the level to log at.
195
     * @param array $context any additional context.
196
     */
197
    protected function log(string $message, string $logLevel = LogLevel::DEBUG, array $context = [])
198
    {
199
        $this->logger->log($logLevel, $message, $context);
200
    }
201
}
202