Reader::readWithPsrHttpClient()   A
last analyzed

Complexity

Conditions 3
Paths 6

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 11
c 0
b 0
f 0
nc 6
nop 3
dl 0
loc 21
ccs 10
cts 10
cp 1
crap 3
rs 9.9
1
<?php
2
3
namespace Enjoys\AssetsCollector\Content;
4
5
use Enjoys\AssetsCollector\Asset;
6
use Enjoys\AssetsCollector\Environment;
7
use Exception;
8
use Psr\Http\Client\ClientInterface;
9
use Psr\Http\Message\RequestFactoryInterface;
10
use Psr\Log\LoggerInterface;
11
use RuntimeException;
12
use Throwable;
13
14
/**
15
 * Class Reader
16
 * @package Enjoys\AssetsCollector\Content
17
 */
18
class Reader
19
{
20
21
22
    private false|string $content;
23
24
25
    private LoggerInterface $logger;
26
27
    /**
28
     * Reader constructor.
29
     * @param Asset $asset
30
     * @param Environment $environment
31
     */
32
    public function __construct(
33
        private readonly Asset $asset,
34
        private readonly Environment $environment,
35
    ) {
36
        $this->logger = $this->environment->getLogger();
37
        $this->content = $this->getContent();
38
    }
39
40
    /**
41
     * @throws Exception
42
     */
43
    public function getContents(): string
44
    {
45 21
        if (!$this->asset->isValid() || $this->content === false) {
46
            $this->logger->notice(sprintf('Nothing return: path is `%s`', $this->asset->getOrigPath()));
47
            return '';
48
        }
49
        return $this->content;
50 21
    }
51 21
52 21
53 21
    private function getContent(): false|string
54 21
    {
55
        if (!$this->asset->isValid()) {
56
            return false;
57
        }
58
59
        if ($this->asset->isUrl()) {
60 13
            return $this->readUrl($this->asset->getPath());
61
        }
62 13
        return $this->readFile($this->asset->getPath());
63 4
    }
64 4
65
66 9
    private function readUrl(string $url): false|string
67
    {
68
        if (
69
            null !== ($httpClient = $this->environment->getHttpClient())
70
            && null !== ($requestFactory = $this->environment->getRequestFactory())
71
        ) {
72
            return $this->readWithPsrHttpClient($url, $httpClient, $requestFactory);
73 21
        }
74
75 21
        try {
76 1
            return $this->readWithPhpFileGetContents($url);
77
        } catch (RuntimeException $e) {
78
            $this->logger->notice(sprintf("Ошибка чтения содержимого файла: %s", $e->getMessage()));
79 20
            return false;
80 4
        }
81
    }
82 16
83
    /**
84
     * @throws RuntimeException
85
     */
86
    private function readWithPhpFileGetContents(string $url): false|string
87
    {
88 4
        //Clear the most recent error
89
        error_clear_last();
90
        $content = @file_get_contents($url);
91 4
        /** @var null|string[] $error */
92 4
        $error = error_get_last();
93
        if ($error !== null) {
94 2
            throw new RuntimeException(sprintf("%s", $error['message']));
95
        }
96
        return $content;
97 2
    }
98
99
100
    private function readWithPsrHttpClient(
101
        string $url,
102
        ClientInterface $client,
103
        RequestFactoryInterface $requestFactory
104 18
    ): false|string {
105
        try {
106
            $response = $client->sendRequest(
107
                $requestFactory->createRequest('get', $url)
108 18
            );
109 18
110
            if ($response->getStatusCode() !== 200) {
111 18
                throw new RuntimeException(
112 18
                    sprintf('HTTP error: %s - %s', $response->getStatusCode(), $response->getReasonPhrase())
113 2
                );
114
            }
115 16
116 2
            $this->logger->info(sprintf('Read: %s', $url));
117 2
            return $response->getBody()->getContents();
118 2
        } catch (Throwable $e) {
119
            $this->logger->notice($e->getMessage());
120
            return false;
121
        }
122
    }
123
124
    private function readFile(string $filename): false|string
125 2
    {
126
        if (!file_exists($filename)) {
127
            $this->logger->notice(sprintf("Файла по указанному пути нет: %s", $filename));
128
            return false;
129
        }
130
131 2
        try {
132 2
            $content = $this->readWithPhpFileGetContents($filename);
133 2
        } catch (RuntimeException $e) {
134
            $this->logger->notice(sprintf("Ошибка чтения содержимого файла: %s", $e->getMessage()));
135 2
            return false;
136 1
        }
137 1
138 1
        $this->logger->info(sprintf('Read: %s', $filename));
139
        return $content;
140
    }
141 1
142 1
    /**
143 1
     * @throws Exception
144 1
     */
145 1
    public function replaceRelativeUrls(): Reader
146
    {
147
        if (!$this->asset->isValid() || $this->content === false) {
148
            return $this;
149
        }
150
151
        if ($this->asset->getOptions()->isReplaceRelativeUrls()) {
152
            $replaceRelativeUrls = new ReplaceRelative($this->content, $this->asset, $this->environment);
153 16
            $this->content = $replaceRelativeUrls->getContent();
154
        }
155 16
156
        return $this;
157
    }
158
159
160
    public function minify(): Reader
161 16
    {
162
        if (!$this->asset->isValid() || $this->content === false || !$this->asset->getOptions()->isMinify()) {
163
            return $this;
164
        }
165
166
        $minifier = $this->environment->getMinifier($this->asset->getType());
167 16
168 16
        if ($minifier === null) {
169
            return $this;
170
        }
171
172
        $this->logger->info(sprintf('Minify: %s', $this->asset->getPath()));
173
174
        $this->content = $minifier->minify($this->content) . "\n";
175
        return $this;
176
    }
177
}
178