Completed
Push — develop ( e326d5...b2cbdf )
by Daniel
09:21
created

ContentFactory::__construct()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 18
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 16
nc 1
nop 3
dl 0
loc 18
rs 9.7333
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Silverback\ApiComponentBundle\Factory;
6
7
use GuzzleHttp\Client;
8
use GuzzleHttp\Exception\RequestException;
9
use Silverback\ApiComponentBundle\Entity\Component\Content\Content;
10
11
class ContentFactory
12
{
13
    private $client;
14
    private $lipsumOps;
15
    private $guzzleOps;
16
17
    public function __construct(Client $client, ?array $lipsumOps = null, array $guzzleOps = []) {
18
        $this->client = $client;
19
        $this->lipsumOps = $lipsumOps ?: [
20
            '5',
21
            'medium',
22
            'headers',
23
            'code',
24
            'decorate',
25
            'link',
26
            'bq',
27
            'ul',
28
            'ol'
29
        ];
30
        $this->guzzleOps = array_merge([
31
            'connect_timeout' => 3,
32
            'read_timeout' => 2,
33
            'timeout' => 5
34
        ], $guzzleOps);
35
    }
36
37
    public function create(?Content $contentEntity = null, ?array $lipsumOps = null, array $guzzleOps = [])
38
    {
39
        $lipsumOps = $lipsumOps ?: $this->lipsumOps;
40
        $guzzleOps = array_merge($this->guzzleOps, $guzzleOps);
41
        $content = $contentEntity ?: new Content();
42
        $content->setContent($this->getLipsumContent($lipsumOps, $guzzleOps));
43
        return $content;
44
    }
45
46
    /**
47
     * @return string
48
     */
49
    private function getLipsumContent(array $lipsumOps, array $guzzleOps): string
50
    {
51
        $url = 'https://loripsum.net/api/' . implode('/', $lipsumOps);
52
        try {
53
            $res = $this->client->request(
54
                'GET',
55
                $url,
56
                $guzzleOps
57
            );
58
            return (string) $res->getBody();
59
        } catch (RequestException $e) {
60
            return vsprintf(
61
                '<p><b>Request Exception</b>: %s<br/><small><a href="%s">%s</a></small></p>',
62
                [
63
                    $e->getMessage(),
64
                    $url,
65
                    $url
66
                ]
67
            );
68
        }
69
    }
70
}