aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/vendor/splitbrain/lesserphp/src/Functions/Strings.php
blob: a91160d90542914e50d662bc445fd4c7b7deae04 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php

namespace LesserPHP\Functions;

use Exception;
use LesserPHP\Utils\Color;
use LesserPHP\Utils\Util;

/**
 * Implements the string functions for LESS
 *
 * @link https://lesscss.org/functions/#string-functions
 */
class Strings extends AbstractFunctionCollection
{
    /** @inheritdoc */
    public function getFunctions(): array
    {
        return [
            //'escape' => [$this, 'escape'],
            'e' => [$this, 'e'],
            '%' => [$this, 'format'],
            //'replace' => [$this, 'replace'],
        ];
    }


    // escape is missing

    /**
     * String escaping.
     *
     * It expects string as a parameter and return its content as is, but without quotes. It can be used
     * to output CSS value which is either not valid CSS syntax, or uses proprietary syntax which
     * Less doesn't recognize.
     *
     * @link https://lesscss.org/functions/#string-functions-e
     * @throws Exception
     */
    public function e(array $arg): array
    {
        return $this->lessc->unwrap($arg);
    }

    /**
     * Formats a string
     *
     * @link https://lesscss.org/functions/#string-functions--format
     * @throws Exception
     */
    public function format(array $args) : array
    {
        if ($args[0] != 'list') return $args;
        $values = $args[2];
        $string = array_shift($values);
        $template = $this->lessc->compileValue($this->lessc->unwrap($string));

        $i = 0;
        if (preg_match_all('/%[dsa]/', $template, $m)) {
            foreach ($m[0] as $match) {
                $val = isset($values[$i]) ?
                    $this->lessc->reduce($values[$i]) : ['keyword', ''];

                // lessjs compat, renders fully expanded color, not raw color
                if ($color = Color::coerceColor($val)) {
                    $val = $color;
                }

                $i++;
                $rep = $this->lessc->compileValue($this->lessc->unwrap($val));
                $template = preg_replace(
                    '/' . Util::pregQuote($match) . '/',
                    $rep,
                    $template,
                    1
                );
            }
        }

        $d = $string[0] == 'string' ? $string[1] : '"';
        return ['string', $d, [$template]];
    }

    // replace is missing
}