1 <?php
2
3 /*
4 * This file is part of the Brickrouge package.
5 *
6 * (c) Olivier Laviale <olivier.laviale@gmail.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Brickrouge;
13
14 /**
15 * An interface to a _Decorator_ design pattern used to decorate HTML strings and objects that
16 * render as HTML strings.
17 */
18 interface DecoratorInterface
19 {
20 /**
21 * Renders the component.
22 */
23 public function render();
24
25 /**
26 * Renders the component into a string.
27 */
28 public function __toString();
29 }
30
31 /**
32 * Decorates the specified component.
33 */
34 abstract class Decorator implements DecoratorInterface
35 {
36 /**
37 * The component to decorate.
38 *
39 * @var mixed
40 */
41 protected $component;
42
43 /**
44 * Initializes the {@link $component} property.
45 *
46 * @param mixed $component
47 */
48 public function __construct($component)
49 {
50 $this->component = $component;
51 }
52
53 /**
54 * Renders the component.
55 *
56 * @return mixed The component supplied during {@link __construct} is returned as is.
57 */
58 public function render()
59 {
60 return $this->component;
61 }
62
63 /**
64 * Renders the component into a string.
65 *
66 * The component is rendered by calling the {@link render()} method and casting the result
67 * into a string. If an exception is raised during this process, the exception is rendered
68 * with the {@link render_exception()} function and the rendered exception is returned.
69 *
70 * @return string
71 */
72 public function __toString()
73 {
74 try
75 {
76 return (string) $this->render();
77 }
78 catch (\Exception $e)
79 {
80 return render_exception($e);
81 }
82 }
83 }