Passed
Push — assets ( 3fff95...52bc9a )
by Arnaud
03:06
created

Asset::__construct()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 4
eloc 14
c 4
b 0
f 0
nc 3
nop 3
dl 0
loc 23
rs 9.7998
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 $data = [];
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
        $attributs = null; // html attributes
45
        extract(is_array($options) ? $options : [], EXTR_IF_EXISTS);
46
47
        // set data
48
        $this->data['file'] = $filePath;
49
        $this->data['path'] = '/'.ltrim($path, '/');
50
        $this->data['ext'] = pathinfo($filePath, PATHINFO_EXTENSION);
51
        $this->data['type'] = explode('/', mime_content_type($filePath))[0];
52
        $this->data['content'] = null;
53
        if ($this->data['type'] == 'text') {
54
            $this->data['content'] = file_get_contents($filePath);
55
        }
56
        $this->data['attributs'] = $attributs;
57
    }
58
59
    /**
60
     * @return string
61
     */
62
    public function __toString(): string
63
    {
64
        return $this->data['path'];
65
    }
66
67
    /**
68
     * Implements \ArrayAccess.
69
     */
70
    public function offsetSet($offset, $value)
71
    {
72
        if (!is_null($offset)) {
73
            $this->data[$offset] = $value;
74
        }
75
    }
76
77
    /**
78
     * Implements \ArrayAccess.
79
     */
80
    public function offsetExists($offset)
81
    {
82
        return isset($this->data[$offset]);
83
    }
84
85
    /**
86
     * Implements \ArrayAccess.
87
     */
88
    public function offsetUnset($offset)
89
    {
90
        unset($this->data[$offset]);
91
    }
92
93
    /**
94
     * Implements \ArrayAccess.
95
     */
96
    public function offsetGet($offset)
97
    {
98
        return isset($this->data[$offset]) ? $this->data[$offset] : null;
99
    }
100
101
    /**
102
     * Returns as HTML tag.
103
     *
104
     * @return string
105
     */
106
    public function getHtml(): string
107
    {
108
        if ($this->data['type'] == 'image') {
109
            $title = array_key_exists('title', $this->data['attributs']) ? $this->data['attributs']['title'] : null;
110
            $alt = array_key_exists('alt', $this->data['attributs']) ? $this->data['attributs']['alt'] : null;
111
112
            return \sprintf(
113
                '<img src="%s"%s%s>',
114
                $this->data['path'],
115
                !is_null($title) ? \sprintf(' title="%s"', $title) : '',
116
                !is_null($alt) ? \sprintf(' alt="%s"', $alt) : ''
117
            );
118
        }
119
120
        switch ($this->data['ext']) {
121
            case 'css':
122
                return \sprintf('<link rel="stylesheet" href="%s">', $this->data['path']);
123
            case 'js':
124
                return \sprintf('<script src="%s"></script>', $this->data['path']);
125
        }
126
127
        throw new Exception(\sprintf('%s is available only with CSS, JS and images files.', '.html'));
128
    }
129
130
    /**
131
     * Returns file's content.
132
     *
133
     * @return string
134
     */
135
    public function getInline(): string
136
    {
137
        if (is_null($this->data['content'])) {
138
            throw new Exception(\sprintf('%s is available only with CSS et JS files.', '.inline'));
139
        }
140
141
        return $this->data['content'];
142
    }
143
144
    /**
145
     * Try to find a static file (in site or theme(s)) if exists or returns false.
146
     *
147
     * @param string $path
148
     *
149
     * @return string|false
150
     */
151
    private function findFile(string $path)
152
    {
153
        $filePath = Util::joinFile($this->config->getStaticPath(), $path);
154
        if (Util::getFS()->exists($filePath)) {
155
            return $filePath;
156
        }
157
158
        // checks in each theme
159
        foreach ($this->config->getTheme() as $theme) {
160
            $filePath = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $path);
161
            if (Util::getFS()->exists($filePath)) {
162
                return $filePath;
163
            }
164
        }
165
166
        return false;
167
    }
168
}
169