PageRenderTime 29ms CodeModel.GetById 17ms app.highlight 7ms RepoModel.GetById 2ms app.codeStats 0ms

/administrator/components/com_widgetkit/vendor/yootheme/framework/src/View/Asset/Filter/CssImageBase64Filter.php

https://gitlab.com/vnsoftdev/amms
PHP | 62 lines | 35 code | 11 blank | 16 comment | 5 complexity | 53b042790b51bf9491e7ec02892684ed MD5 | raw file
 1<?php
 2
 3namespace YOOtheme\Framework\View\Asset\Filter;
 4
 5use YOOtheme\Framework\Routing\Request;
 6use YOOtheme\Framework\View\Asset\AssetInterface;
 7
 8class CssImageBase64Filter implements FilterInterface
 9{
10    /**
11     * @var string
12     */
13    protected $baseUrl;
14
15    /**
16     * @var string
17     */
18    protected $basePath;
19
20    /**
21     * Constructor.
22     *
23     * @param Request $request
24     */
25    public function __construct(Request $request)
26    {
27        $this->baseUrl  = parse_url($request->getBaseUrl(), PHP_URL_PATH);
28        $this->basePath = $request->getBasePath();
29    }
30
31    /**
32     * {@inheritdoc}
33     */
34    public function filterContent(AssetInterface $asset)
35    {
36        $images  = array();
37        $content = $asset->getContent();
38
39        // get images and the related path
40        if (preg_match_all('/url\(\s*[\'"]?([^\'"]+)[\'"]?\s*\)/Ui', $asset->getContent(), $matches)) {
41            foreach ($matches[0] as $i => $url) {
42
43                if (strpos($path = $matches[1][$i], $this->baseUrl) !== 0) {
44                    continue;
45                }
46
47                if ($path = realpath($this->basePath.'/'.ltrim(substr($path, strlen($this->baseUrl)), '/'))) {
48                    $images[$url] = $path;
49                }
50            }
51        }
52
53        // check if image exists and filesize < 10kb
54        foreach ($images as $url => $path) {
55            if (filesize($path) <= 10240 && preg_match('/\.(gif|png|jpg)$/i', $path, $extension)) {
56                $content = str_replace($url, sprintf('url(data:image/%s;base64,%s)', str_replace('jpg', 'jpeg', strtolower($extension[1])), base64_encode(file_get_contents($path))), $content);
57            }
58        }
59
60        $asset->setContent($content);
61    }
62}