RewriteCssUrls::filter()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 22
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 16
c 1
b 0
f 0
nc 2
nop 3
dl 0
loc 22
rs 9.7333
1
<?php
2
/**
3
 * laravel-assets: asset management for Laravel 5
4
 *
5
 * Copyright (c) 2021 Greg Roach
6
 *
7
 * This program is free software: you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation, either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19
 */
20
21
namespace Fisharebest\LaravelAssets\Filters;
22
23
use Fisharebest\LaravelAssets\Assets;
24
use Fisharebest\LaravelAssets\SetStateTrait;
25
26
class RewriteCssUrls implements FilterInterface
27
{
28
    use SetStateTrait;
29
30
    /**
31
     * Rewrite relative URLs in CSS files to take account of their new location.
32
     *
33
     * CSS files may contain relative URLs, such as "background-image: url(img.jpg)".
34
     * If our processed CSS file is in a different location, such as "min" instead of
35
     * "css", then we must rewrite this to "background-image: url(../css/img.jpg)".
36
     *
37
     * @param string $data      The data to be filtered
38
     * @param string $asset_url The original URL for this data
39
     * @param Assets $assets    The asset manager object, for access to its config settings and utilities
40
     *
41
     * @return string
42
     */
43
    public function filter($data, $asset_url, $assets)
44
    {
45
        if ($assets->isAbsoluteUrl($asset_url)) {
46
            $prefix = dirname($asset_url);
47
        } else {
48
            $destination = $assets->getCssSource() . '/' . dirname($asset_url);
49
            $prefix      = $assets->relativePath($assets->getDestination(), $destination);
50
        }
51
52
        $data = preg_replace_callback([
53
            '/(\burl\s*\(\s*")([^"]+?)("\s*\))/',
54
            '/(\burl\s*\(\s*\')([^\']+?)(\'\s*\))/',
55
            '/(\burl\s*\(\s*)([^\'"]+?)(\s*\))/',
56
        ], function ($matches) use ($assets, $prefix) {
57
            if ($assets->isAbsoluteUrl($matches[2])) {
58
                return $matches[0];
59
            } else {
60
                return $matches[1] . $assets->normalizePath($prefix . '/' . $matches[2]) . $matches[3];
61
            }
62
        }, $data);
63
64
        return $data;
65
    }
66
}
67