AbstractApi::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace OneSignal;
6
7
use JsonException;
8
use OneSignal\Exception\InvalidArgumentException;
9
use Psr\Http\Message\RequestInterface;
10
use Psr\Http\Message\StreamInterface;
11
use const JSON_THROW_ON_ERROR;
12
13
abstract class AbstractApi
14
{
15
    /**
16
     * @var OneSignal
17
     */
18
    protected $client;
19
20
    public function __construct(OneSignal $client)
21
    {
22
        $this->client = $client;
23
    }
24
25
    protected function createRequest(string $method, string $uri): RequestInterface
26
    {
27
        $request = $this->client->getRequestFactory()->createRequest($method, OneSignal::API_URL.$uri);
28
        $request = $request->withHeader('Accept', 'application/json');
29
30
        return $request;
31
    }
32
33
    /**
34
     * @param mixed $value
35
     */
36
    protected function createStream($value, int $flags = null, int $maxDepth = 512): StreamInterface
37
    {
38
        $flags = $flags ?? (JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_PRESERVE_ZERO_FRACTION);
39
40
        try {
41
            $value = json_encode($value, $flags | JSON_THROW_ON_ERROR, $maxDepth);
42
        } catch (JsonException $e) {
43
            throw new InvalidArgumentException("Invalid value for json encoding: {$e->getMessage()}.");
44
        }
45
46
        return $this->client->getStreamFactory()->createStream($value);
47
    }
48
}
49