Passed
Push — master ( a8959a...ad2bf9 )
by Enjoys
01:55
created

Reader::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 1
eloc 5
c 2
b 1
f 0
nc 1
nop 4
dl 0
loc 12
ccs 6
cts 6
cp 1
crap 1
rs 10
1
<?php
2
3
namespace Enjoys\AssetsCollector\Content;
4
5
use Enjoys\AssetsCollector\Asset;
6
use Enjoys\AssetsCollector\Content\Minify\MinifyFactory;
7
use Enjoys\AssetsCollector\Environment;
8
use GuzzleHttp\Client;
9
use GuzzleHttp\Exception\ClientException;
10
use GuzzleHttp\Exception\GuzzleException;
11
use Psr\Log\LoggerInterface;
12
use Psr\Log\NullLogger;
13
14
/**
15
 * Class Reader
16
 * @package Enjoys\AssetsCollector\Content
17
 */
18
class Reader
19
{
20
    /**
21
     * @var Asset
22
     */
23
    private Asset $asset;
24
25
    /**
26
     * @var false|string
27
     */
28
    private $content;
29
30
    /**
31
     * @var array{css: array, js: array}
32
     */
33
    private array $minifyOptions;
34
    private Environment $environment;
35
    /**
36
     * @var LoggerInterface|NullLogger
37
     */
38
    private LoggerInterface $logger;
39
40
    /**
41
     * Reader constructor.
42
     * @param Asset $asset
43
     * @param array{css: array, js: array} $minifyOptions
44
     * @param Environment $environment
45
     * @param LoggerInterface|null $logger
46
     */
47 6
    public function __construct(
48
        Asset $asset,
49
        array $minifyOptions,
50
        Environment $environment,
51
        LoggerInterface $logger = null
52
    ) {
53 6
        $this->environment = $environment;
54 6
        $this->asset = $asset;
55 6
        $this->logger = $logger ?? new NullLogger();
56
57 6
        $this->content = $this->getContent();
58 6
        $this->minifyOptions = $minifyOptions;
59 6
    }
60
61
    /**
62
     * @throws \Exception
63
     */
64 6
    public function getContents(): string
65
    {
66 6
        $path = $this->asset->getPath();
67
68 6
        if ($this->content === false || $path === false) {
69 2
            $this->logger->notice(sprintf('Nothing return: path is `%s`', (string)$path));
70 2
            return '';
71
        }
72
73 4
        if ($this->asset->isUrl()) {
74
            $replaceRelativeUrls = new ReplaceRelativeUrls($this->content, $path);
0 ignored issues
show
Bug introduced by
It seems like $this->content can also be of type true; however, parameter $content of Enjoys\AssetsCollector\C...tiveUrls::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

74
            $replaceRelativeUrls = new ReplaceRelativeUrls(/** @scrutinizer ignore-type */ $this->content, $path);
Loading history...
75
            $replaceRelativeUrls->setLogger($this->logger);
76
            $this->content = $replaceRelativeUrls->getContent();
77
        } else {
78 4
            $replaceRelativePath = new ReplaceRelativePaths(
79 4
                $this->content,
0 ignored issues
show
Bug introduced by
It seems like $this->content can also be of type true; however, parameter $content of Enjoys\AssetsCollector\C...ivePaths::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

79
                /** @scrutinizer ignore-type */ $this->content,
Loading history...
80
                $path,
81 4
                $this->environment
82
            );
83 4
            $replaceRelativePath->setLogger($this->logger);
84 4
            $this->content = $replaceRelativePath->getContent();
85
        }
86
87 4
        if ($this->asset->isMinify()) {
88 2
            $this->content = MinifyFactory::minify(
89 2
                $this->content,
90 2
                $this->asset->getType(),
91 2
                $this->minifyOptions
92 2
            )->getContent() . "\n";
93 2
            $this->logger->info(sprintf('Minify: %s', $path));
94
        }
95 4
        return $this->content;
96
    }
97
98
99
    /**
100
     * @return false|string
101
     */
102 6
    private function getContent()
103
    {
104 6
        if (false !== $path = $this->asset->getPath()) {
0 ignored issues
show
introduced by
The condition false !== $path = $this->asset->getPath() is always true.
Loading history...
105 5
            if ($this->asset->isUrl()) {
106
                return $this->readUrl($path);
107
            }
108 5
            return $this->readFile($path);
109
        }
110 1
        return false;
111
    }
112
113
    /**
114
     * @param string $url
115
     * @return false|string
116
     */
117
    private function readUrl(string $url)
118
    {
119
        try {
120
            $client = new Client(
121
                [
122
                    'verify' => false,
123
                    'allow_redirects' => true,
124
                    'headers' => [
125
                        'User-Agent' =>
126
                            'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
127
                    ]
128
                ]
129
            );
130
            $response = $client->get($url);
131
            $this->logger->info(sprintf('Read: %s', $url));
132
            return $response->getBody()->getContents();
133
        } catch (ClientException | GuzzleException $e) {
134
            $this->logger->notice($e->getMessage());
135
            return false;
136
        }
137
    }
138
139
    /**
140
     * @param string $filename
141
     * @return false|string
142
     */
143 5
    private function readFile(string $filename)
144
    {
145
        //Clear the most recent error
146 5
        error_clear_last();
147
148 5
        if (!file_exists($filename)) {
149
            $this->logger->notice(sprintf("Файла по указанному пути нет: %s", $filename));
150
            return false;
151
        }
152 5
        $content = @file_get_contents($filename);
153
154
        /** @var null|string[] $error */
155 5
        $error = error_get_last();
156 5
        if ($error !== null) {
157 1
            $this->logger->notice(sprintf("Ошибка чтения содержимого файла: %s", $error['message']));
158 1
            return false;
159
        }
160
161 4
        $this->logger->info(sprintf('Read: %s', $filename));
162 4
        return $content;
163
    }
164
165
    /**
166
     * @param LoggerInterface|NullLogger $logger
167
     */
168
    public function setLogger($logger): void
169
    {
170
        $this->logger = $logger;
171
    }
172
}
173