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 `<INPUT>` element of type `text`.
16 *
17 * One can override the `type` attribute to use a different kind of input, such as `password`.
18 */
19 class Text extends Element
20 {
21 /**
22 * Text inputs—with appended or prepended text—provide an easy way to give more context for
23 * your inputs. Great examples include the `@` sign for Twitter usernames or `€` for finances.
24 *
25 * @var string
26 */
27 const ADDON = '#addon';
28
29 /**
30 * Defines the position of the add-on: `before` or `after`. Defaults to `after`.
31 *
32 * @var string
33 */
34 const ADDON_POSITION = '#addon-position';
35
36 /**
37 * Construct the element with the following initial attributes:
38 *
39 * - type: 'text'
40 *
41 * @param array $attributes
42 *
43 * @see Element::__construct()
44 */
45 public function __construct(array $attributes=array())
46 {
47 parent::__construct
48 (
49 'input', $attributes + array
50 (
51 'type' => 'text'
52 )
53 );
54 }
55
56 /**
57 * Renders the addon.
58 *
59 * @param mixed $addon
60 *
61 * @return string|Element
62 */
63 protected function render_addon($addon)
64 {
65 if ($addon instanceof Button || $addon instanceof DropdownMenu)
66 {
67 return $addon;
68 }
69
70 return <<<EOT
71 <span class="add-on">{$addon}</span>
72 EOT;
73 }
74
75 /**
76 * Decorates the HTML with the add-on specified with the {@link ADDON} attribute.
77 *
78 * @see Element::decorate()
79 */
80 protected function decorate($html)
81 {
82 $addon = $this[self::ADDON];
83
84 if ($addon)
85 {
86 if ($this[self::ADDON_POSITION] == 'before')
87 {
88 $html = $this->decorate_with_prepend($html, $addon);
89 }
90 else
91 {
92 $html = $this->decorate_with_append($html, $addon);
93 }
94 }
95
96 return parent::decorate($html);
97 }
98
99 /**
100 * Prepend the HTML with the add-on.
101 *
102 * @param string $html
103 * @param string $addon
104 *
105 * @return string The decorated HTML.
106 */
107 protected function decorate_with_prepend($html, $addon)
108 {
109 return '<div class="input-prepend">' . $this->render_addon($addon) . $html . '</div>';
110 }
111
112 /**
113 * Append the HTML with the add-on
114 *
115 * @param string $html
116 * @param string $addon
117 *
118 * @return string The decorated HTML.
119 */
120 protected function decorate_with_append($html, $addon)
121 {
122 return '<div class="input-append">' . $html . $this->render_addon($addon) . '</div>';
123 }
124 }