Passed
Push — assets ( ea9ba5...472b96 )
by Arnaud
02:53
created

Asset::getHtml()   B

Complexity

Conditions 8
Paths 7

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 8
eloc 14
c 2
b 0
f 0
nc 7
nop 0
dl 0
loc 22
rs 8.4444
1
<?php
2
/**
3
 * This file is part of the Cecil/Cecil package.
4
 *
5
 * Copyright (c) Arnaud Ligny <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Cecil\Assets;
12
13
use Cecil\Builder;
14
use Cecil\Config;
15
use Cecil\Exception\Exception;
16
use Cecil\Util;
17
18
class Asset implements \ArrayAccess
19
{
20
    /** @var Builder */
21
    protected $builder;
22
    /** @var Config */
23
    protected $config;
24
    /** @var array */
25
    protected $properties = [];
26
27
    /**
28
     * Loads a file.
29
     *
30
     * @param Builder
31
     * @param string     $path
32
     * @param array|null $options
33
     */
34
    public function __construct(Builder $builder, string $path, array $options = null)
35
    {
36
        $this->builder = $builder;
37
        $this->config = $builder->getConfig();
38
39
        if (false === $filePath = $this->findFile($path)) {
40
            throw new Exception(sprintf('Asset file "%s" doesn\'t exist.', $path));
41
        }
42
43
        // handles options
44
        $canonical = null;
45
        $attributs = null;
46
        extract(is_array($options) ? $options : [], EXTR_IF_EXISTS);
47
        // url
48
        $baseurl = (string) $this->config->get('baseurl');
49
        $base = '';
50
        if ((bool) $this->config->get('canonicalurl') || $canonical === true) {
51
            $base = rtrim($baseurl, '/');
52
        }
53
        if ($canonical === false) {
54
            $base = '';
55
        }
56
57
        // prepares properties
58
        $this->properties['file'] = $filePath;
59
        $this->properties['path'] = '/'.ltrim($path, '/');
60
        $this->properties['url'] = $base.'/'.ltrim($path, '/');
61
        $this->properties['ext'] = pathinfo($filePath, PATHINFO_EXTENSION);
62
        $this->properties['type'] = explode('/', mime_content_type($filePath))[0];
63
        $this->properties['content'] = null;
64
        if ($this->properties['type'] == 'text') {
65
            $this->properties['content'] = file_get_contents($filePath);
66
        }
67
        $this->properties['attributs'] = $attributs;
68
    }
69
70
    /**
71
     * @return string
72
     */
73
    public function __toString(): string
74
    {
75
        return $this->properties['path'];
76
    }
77
78
    /**
79
     * Implements \ArrayAccess.
80
     */
81
    public function offsetSet($offset, $value)
82
    {
83
        if (!is_null($offset)) {
84
            $this->properties[$offset] = $value;
85
        }
86
    }
87
88
    /**
89
     * Implements \ArrayAccess.
90
     */
91
    public function offsetExists($offset)
92
    {
93
        return isset($this->properties[$offset]);
94
    }
95
96
    /**
97
     * Implements \ArrayAccess.
98
     */
99
    public function offsetUnset($offset)
100
    {
101
        unset($this->properties[$offset]);
102
    }
103
104
    /**
105
     * Implements \ArrayAccess.
106
     */
107
    public function offsetGet($offset)
108
    {
109
        return isset($this->properties[$offset]) ? $this->properties[$offset] : null;
110
    }
111
112
    /**
113
     * Returns as HTML tag.
114
     *
115
     * @return string
116
     */
117
    public function getHtml(): string
118
    {
119
        if ($this->properties['type'] == 'image') {
120
            $title = array_key_exists('title', $this->properties['attributs']) ? $this->properties['attributs']['title'] : null;
121
            $alt = array_key_exists('alt', $this->properties['attributs']) ? $this->properties['attributs']['alt'] : null;
122
123
            return \sprintf(
124
                '<img src="%s"%s%s>',
125
                $this->properties['path'],
126
                !is_null($title) ? \sprintf(' title="%s"', $title) : '',
127
                !is_null($alt) ? \sprintf(' alt="%s"', $alt) : ''
128
            );
129
        }
130
131
        switch ($this->properties['ext']) {
132
            case 'css':
133
                return \sprintf('<link rel="stylesheet" href="%s">', $this->properties['path']);
134
            case 'js':
135
                return \sprintf('<script src="%s"></script>', $this->properties['path']);
136
        }
137
138
        throw new Exception(\sprintf('%s is available only with CSS, JS and images files.', '.html'));
139
    }
140
141
    /**
142
     * Returns file's content.
143
     *
144
     * @return string
145
     */
146
    public function getInline(): string
147
    {
148
        if (!array_key_exists('content', $this->properties)) {
149
            throw new Exception(\sprintf('%s is available only with CSS et JS files.', '.inline'));
150
        }
151
152
        return $this->properties['content'];
153
    }
154
155
    /**
156
     * Try to find a static file (in site or theme(s)) if exists or returns false.
157
     *
158
     * @param string $path
159
     *
160
     * @return string|false
161
     */
162
    private function findFile(string $path)
163
    {
164
        $filePath = Util::joinFile($this->config->getStaticPath(), $path);
165
        if (Util::getFS()->exists($filePath)) {
166
            return $filePath;
167
        }
168
169
        // checks in each theme
170
        foreach ($this->config->getTheme() as $theme) {
171
            $filePath = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $path);
172
            if (Util::getFS()->exists($filePath)) {
173
                return $filePath;
174
            }
175
        }
176
177
        return false;
178
    }
179
}
180