Completed
Push — master ( 409071...e1997d )
by Marc
03:57
created

Svg::run()   B

Complexity

Conditions 7
Paths 1

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 32
rs 8.4746
c 0
b 0
f 0
cc 7
nc 1
nop 0
1
<?php
2
3
namespace luya\web;
4
5
use luya\base\Widget;
6
use luya\Exception;
7
use luya\helpers\FileHelper;
8
use luya\helpers\StringHelper;
9
use luya\traits\CacheableTrait;
10
use Yii;
11
12
/**
13
 * Svg "inserter"
14
 *
15
 * This Widget will insert the contents of a given SVG file at the widgets position
16
 * or create an svg>use element for a given file + symbol.
17
 *
18
 * Inline the SVG contents:
19
 *
20
 * ```php
21
 *  <?= Svg::widget([
22
 *     'folder' => "@webroot/images/svg",
23
 *     'file' => 'logos/logo.svg',
24
 *     'cssClass' => 'additional-class-for-css'
25
 * ]); ?>
26
 * ```
27
 *
28
 * SVG > Use implementation:
29
 *
30
 * ```php
31
 * <?= Svg::widget([
32
 *     'symbolMode' => true,
33
 *     'symbolName' => 'example'
34
 *     'file' => 'images/svg-sprite.svg',
35
 *     'cssClass' => 'additional-class-for-css'
36
 * ]); ?>
37
 * ```
38
 *
39
 * @property string $folder The base folder path. Default is "@webroot/svg"
40
 *
41
 * @author Marc Stampfli <[email protected]>
42
 * @since 1.0.0
43
 */
44
class Svg extends Widget
45
{
46
    use CacheableTrait;
47
48
    /**
49
     * @var bool If symbolMode is true the widget will create a svg > use
50
     * @since 1.0.12
51
     */
52
    public $symbolMode;
53
54
    /**
55
     * @var string The name of the symbol that will be referenced
56
     * @since 1.0.12
57
     */
58
    public $symbolName;
59
60
    /**
61
     * @var string Relative path to the SVG file based on $folder
62
     */
63
    public $file;
64
65
    /**
66
     * @var string Additional css class to add to the SVG element, use only if the SVG itself has no class
67
     */
68
    public $cssClass;
69
70
    /**
71
     * @var string The base folder path. Default is "@webroot/svg"
72
     */
73
    private $_folder;
74
75
    /**
76
     * Setter method for $folder.
77
     *
78
     * @param string $folder Set folder for the given string (parsed trough Yii::getAlias())
79
     */
80
    public function setFolder($folder)
81
    {
82
        $this->_folder = Yii::getAlias($folder);
0 ignored issues
show
Documentation Bug introduced by
It seems like \Yii::getAlias($folder) can also be of type boolean. However, the property $_folder is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
83
    }
84
85
    /**
86
     * Getter method for $folder.
87
     *
88
     * @return string Returns the folder string, if none is set it will return the default value "@webroot/svg"
89
     */
90
    public function getFolder()
91
    {
92
        if ($this->_folder === null) {
93
            $this->_folder = Yii::getAlias("@webroot/svg");
0 ignored issues
show
Documentation Bug introduced by
It seems like \Yii::getAlias('@webroot/svg') can also be of type boolean. However, the property $_folder is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
94
        }
95
96
        return rtrim($this->_folder, DIRECTORY_SEPARATOR);
97
    }
98
99
    /**
100
     * @inheritdoc
101
     */
102
    public function run()
103
    {
104
        // Cache generated code
105
        return $this->getOrSetHasCache(['svg', $this->folder, $this->file, $this->cssClass], function () {
106
107
            // Check if file ends with .svg, if not add the extension
108
            $svgFile = StringHelper::endsWith($this->file, '.svg') ? $this->file : $this->file . '.svg';
109
110
            if ($this->symbolMode) {
111
                $svgPath = Yii::$app->view->publicHtml . '/' . $svgFile;
112
113
                return '<svg class="symbol symbol--' . $this->symbolName . '' . ($this->cssClass ? ' ' . $this->cssClass : '') . '"><use class="symbol__use" xlink:href="' . $svgPath . '#' . $this->symbolName . '" /></svg>';
114
            } else {
115
                // Build the full svg file path
116
                $svgPath = $this->folder . DIRECTORY_SEPARATOR . $svgFile;
117
118
                // Get the svg contents
119
                $content = FileHelper::getFileContent($svgPath);
120
121
                // If a cssClass string is given, add it to the <svg> tag
122
                if ($this->cssClass && is_string($this->cssClass)) {
123
                    $content = preg_replace('/<svg/', '<svg class="' . $this->cssClass . '"', $content);
124
                }
125
126
                if ($content) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $content of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
127
                    return $content;
128
                }
129
            }
130
131
            throw new Exception('Unable to access SVG File: ' . $svgPath);
132
        });
133
    }
134
}
135