1 <?php
2 /* --------------------------------------------------------------
3 Asset.inc.php 2015-03-13 gm
4 Gambio GmbH
5 http://www.gambio.de
6 Copyright (c) 2015 Gambio GmbH
7 Released under the GNU General Public License (Version 2)
8 [http://www.gnu.org/licenses/gpl-2.0.html]
9 --------------------------------------------------------------
10 */
11
12 MainFactory::load_class('AssetInterface');
13
14 /**
15 * Class Asset
16 *
17 * @category System
18 * @package Http
19 * @subpackage ValueObjects
20 */
21 class Asset implements AssetInterface
22 {
23 /**
24 * JavaScript Asset Type
25 */
26 const JAVASCRIPT = 'javascript';
27
28 /**
29 * CSS Asset Type
30 */
31 const CSS = 'css';
32
33 /**
34 * @var string Asset's relative path.
35 */
36 protected $path;
37
38 /**
39 * @var string Asset's type (defined by the file extension).
40 */
41 protected $type;
42
43
44 /**
45 * Initializes the asset.
46 *
47 * @throws InvalidArgumentException
48 *
49 * @param string $path Relative path to the asset file (relative to the "src" directory).
50 */
51 public function __construct($path)
52 {
53 if(!is_string($path) || empty($path))
54 {
55 throw new InvalidArgumentException('Invalid argument $p_path provided (relative asset path - string expected): '
56 . print_r($path, true));
57 }
58
59 $this->path = (string)$path;
60
61 if(substr($this->path, -3) === '.js')
62 {
63 $this->type = self::JAVASCRIPT;
64 }
65 else if(substr($this->path, -4) === '.css')
66 {
67 $this->type = self::CSS;
68 }
69 else
70 {
71 throw new InvalidArgumentException('Provided asset is not supported, provide JavaScript(.js) and CSS (.css) assets.');
72 }
73 }
74
75
76 /**
77 * Get asset HTML markup.
78 *
79 * @return string Returns the HTML markup that will load the file when the page is loaded.
80 */
81 public function __toString()
82 {
83 switch($this->type)
84 {
85 case self::JAVASCRIPT:
86 return '<script type="text/javascript" src="' . $this->path . '"></script>';
87 break;
88 case self::CSS:
89 return '<link rel="stylesheet" type="text/css" href="' . $this->path . '" />';
90 break;
91 default:
92 return ''; // Just in case the asset type was not set correctly.
93 }
94 }
95 }