Merge pull request #7605 from monishdeb/CRM-17685
[civicrm-core.git] / Civi / Token / TokenRow.php
1 <?php
2 namespace Civi\Token;
3
4 /**
5 * Class TokenRow
6 * @package Civi\Token
7 *
8 * A TokenRow is a helper providing simplified access to the
9 * TokenProcessor.
10 *
11 * A TokenRow combines two elements:
12 * - context: This is backend data provided by the controller.
13 * - tokens: This is frontend data that can be mail-merged.
14 *
15 * The context and tokens can be accessed using either methods
16 * or attributes. The methods are appropriate for updates
17 * (and generally accept a mix of arrays), and the attributes
18 * are appropriate for reads.
19 *
20 * To update the context or the tokens, use the methods.
21 * Note that the methods are fairly flexible about accepting
22 * single values or arrays. If given an array, the values
23 * will be merged recursively.
24 *
25 * @code
26 * $row
27 * ->context('contact_id', 123)
28 * ->context(array('contact_id' => 123))
29 * ->tokens('profile', array('viewUrl' => 'http://example.com'))
30 * ->tokens('profile', 'viewUrl, 'http://example.com');
31 *
32 * echo $row->context['contact_id'];
33 * echo $row->tokens['profile']['viewUrl'];
34 *
35 * $row->tokens('profile', array(
36 * 'viewUrl' => 'http://example.com/view/' . urlencode($row->context['contact_id'];
37 * ));
38 * @endcode
39 */
40 class TokenRow {
41
42 /**
43 * @var TokenProcessor
44 */
45 public $tokenProcessor;
46
47 public $tokenRow;
48
49 public $format;
50
51 /**
52 * @var array|\ArrayAccess
53 * List of token values.
54 * Ex: array('contact' => array('display_name' => 'Alice')).
55 */
56 public $tokens;
57
58 /**
59 * @var array|\ArrayAccess
60 * List of context values.
61 * Ex: array('controller' => 'CRM_Foo_Bar').
62 */
63 public $context;
64
65 public function __construct(TokenProcessor $tokenProcessor, $key) {
66 $this->tokenProcessor = $tokenProcessor;
67 $this->tokenRow = $key;
68 $this->format('text/plain'); // Set a default.
69 $this->context = new TokenRowContext($tokenProcessor, $key);
70 }
71
72 /**
73 * @param string $format
74 * @return $this
75 */
76 public function format($format) {
77 $this->format = $format;
78 $this->tokens = &$this->tokenProcessor->rowValues[$this->tokenRow][$format];
79 return $this;
80 }
81
82 /**
83 * Update the value of a context element.
84 *
85 * @param string|array $a
86 * @param mixed $b
87 * @return $this
88 */
89 public function context($a = NULL, $b = NULL) {
90 if (is_array($a)) {
91 \CRM_Utils_Array::extend($this->tokenProcessor->rowContexts[$this->tokenRow], $a);
92 }
93 elseif (is_array($b)) {
94 \CRM_Utils_Array::extend($this->tokenProcessor->rowContexts[$this->tokenRow][$a], $b);
95 }
96 else {
97 $this->tokenProcessor->rowContexts[$this->tokenRow][$a] = $b;
98 }
99 return $this;
100 }
101
102 /**
103 * Update the value of a token.
104 *
105 * @param string|array $a
106 * @param string|array $b
107 * @param mixed $c
108 * @return $this
109 */
110 public function tokens($a = NULL, $b = NULL, $c = NULL) {
111 if (is_array($a)) {
112 \CRM_Utils_Array::extend($this->tokens, $a);
113 }
114 elseif (is_array($b)) {
115 \CRM_Utils_Array::extend($this->tokens[$a], $b);
116 }
117 elseif (is_array($c)) {
118 \CRM_Utils_Array::extend($this->tokens[$a][$b], $c);
119 }
120 elseif ($c === NULL) {
121 $this->tokens[$a] = $b;
122 }
123 else {
124 $this->tokens[$a][$b] = $c;
125 }
126 return $this;
127 }
128
129 /**
130 * Update the value of a token. Apply formatting based on DB schema.
131 *
132 * @param string $tokenEntity
133 * @param string $tokenField
134 * @param string $baoName
135 * @param array $baoField
136 * @param mixed $fieldValue
137 */
138 public function dbToken($tokenEntity, $tokenField, $baoName, $baoField, $fieldValue) {
139 if ($fieldValue === NULL || $fieldValue === '') {
140 return $this->tokens($tokenEntity, $tokenField, '');
141 }
142
143 $fields = $baoName::fields();
144 if (!empty($fields[$baoField]['pseudoconstant'])) {
145 $options = $baoName::buildOptions($baoField, 'get');
146 return $this->format('text/plain')->tokens($tokenEntity, $tokenField, $options[$fieldValue]);
147 }
148
149 switch ($fields[$baoField]['type']) {
150 case \CRM_Utils_Type::T_DATE + \CRM_Utils_Type::T_TIME:
151 return $this->format('text/plain')->tokens($tokenEntity, $tokenField, \CRM_Utils_Date::customFormat($fieldValue));
152
153 case \CRM_Utils_Type::T_MONEY:
154 // Is this something you should ever use? Seems like you need more context
155 // to know which currency to use.
156 return $this->format('text/plain')->tokens($tokenEntity, $tokenField, \CRM_Utils_Money::format($fieldValue));
157
158 case \CRM_Utils_Type::T_STRING:
159 case \CRM_Utils_Type::T_BOOLEAN:
160 case \CRM_Utils_Type::T_INT:
161 case \CRM_Utils_Type::T_TEXT:
162 return $this->format('text/plain')->tokens($tokenEntity, $tokenField, $fieldValue);
163
164 }
165
166 throw new \CRM_Core_Exception("Cannot format token for field '$baoField' in '$baoName'");
167 }
168
169 /**
170 * Auto-convert between different formats
171 *
172 * @param string $format
173 *
174 * @return $this
175 */
176 public function fill($format = NULL) {
177 if ($format === NULL) {
178 $format = $this->format;
179 }
180
181 if (!isset($this->tokenProcessor->rowValues[$this->tokenRow]['text/html'])) {
182 $this->tokenProcessor->rowValues[$this->tokenRow]['text/html'] = array();
183 }
184 if (!isset($this->tokenProcessor->rowValues[$this->tokenRow]['text/plain'])) {
185 $this->tokenProcessor->rowValues[$this->tokenRow]['text/plain'] = array();
186 }
187
188 $htmlTokens = &$this->tokenProcessor->rowValues[$this->tokenRow]['text/html'];
189 $textTokens = &$this->tokenProcessor->rowValues[$this->tokenRow]['text/plain'];
190
191 switch ($format) {
192 case 'text/html':
193 // Plain => HTML.
194 foreach ($textTokens as $entity => $values) {
195 foreach ($values as $field => $value) {
196 if (!isset($htmlTokens[$entity][$field])) {
197 $htmlTokens[$entity][$field] = htmlentities($value);
198 }
199 }
200 }
201 break;
202
203 case 'text/plain':
204 // HTML => Plain.
205 foreach ($htmlTokens as $entity => $values) {
206 foreach ($values as $field => $value) {
207 if (!isset($textTokens[$entity][$field])) {
208 $textTokens[$entity][$field] = html_entity_decode(strip_tags($value));
209 }
210 }
211 }
212 break;
213
214 default:
215 throw new \RuntimeException("Invalid format");
216 }
217
218 return $this;
219 }
220
221 /**
222 * Render a message.
223 *
224 * @param string $name
225 * The name previously registered with TokenProcessor::addMessage.
226 * @return string
227 * Fully rendered message, with tokens merged.
228 */
229 public function render($name) {
230 return $this->tokenProcessor->render($name, $this);
231 }
232
233 }
234
235 /**
236 * Class TokenRowContext
237 * @package Civi\Token
238 *
239 * Combine the row-context and general-context into a single array-like facade.
240 */
241 class TokenRowContext implements \ArrayAccess, \IteratorAggregate, \Countable {
242
243 /**
244 * @var TokenProcessor
245 */
246 protected $tokenProcessor;
247
248 protected $tokenRow;
249
250 /**
251 * Class constructor.
252 *
253 * @param array $tokenProcessor
254 * @param array $tokenRow
255 */
256 public function __construct($tokenProcessor, $tokenRow) {
257 $this->tokenProcessor = $tokenProcessor;
258 $this->tokenRow = $tokenRow;
259 }
260
261 /**
262 * Does offset exist.
263 *
264 * @param mixed $offset
265 *
266 * @return bool
267 */
268 public function offsetExists($offset) {
269 return
270 isset($this->tokenProcessor->rowContexts[$this->tokenRow][$offset])
271 || isset($this->tokenProcessor->context[$offset]);
272 }
273
274 /**
275 * Get offset.
276 *
277 * @param string $offset
278 *
279 * @return string
280 */
281 public function &offsetGet($offset) {
282 if (isset($this->tokenProcessor->rowContexts[$this->tokenRow][$offset])) {
283 return $this->tokenProcessor->rowContexts[$this->tokenRow][$offset];
284 }
285 if (isset($this->tokenProcessor->context[$offset])) {
286 return $this->tokenProcessor->context[$offset];
287 }
288 $val = NULL;
289 return $val;
290 }
291
292 /**
293 * Set offset.
294 *
295 * @param string $offset
296 * @param mixed $value
297 */
298 public function offsetSet($offset, $value) {
299 $this->tokenProcessor->rowContexts[$this->tokenRow][$offset] = $value;
300 }
301
302 /**
303 * Unset offset.
304 *
305 * @param mixed $offset
306 */
307 public function offsetUnset($offset) {
308 unset($this->tokenProcessor->rowContexts[$this->tokenRow][$offset]);
309 }
310
311 /**
312 * Get iterator.
313 *
314 * @return \ArrayIterator
315 */
316 public function getIterator() {
317 return new \ArrayIterator($this->createMergedArray());
318 }
319
320 /**
321 * Count.
322 *
323 * @return int
324 */
325 public function count() {
326 return count($this->createMergedArray());
327 }
328
329 /**
330 * Create merged array.
331 *
332 * @return array
333 */
334 protected function createMergedArray() {
335 return array_merge(
336 $this->tokenProcessor->rowContexts[$this->tokenRow],
337 $this->tokenProcessor->context
338 );
339 }
340
341 }