4 use Civi\Token\Event\TokenRegisterEvent
;
5 use Civi\Token\Event\TokenRenderEvent
;
6 use Civi\Token\Event\TokenValueEvent
;
7 use Symfony\Component\EventDispatcher\EventDispatcherInterface
;
10 class TokenProcessor
{
14 * Description of the context in which the tokens are being processed.
15 * Ex: Array('class'=>'CRM_Core_BAO_ActionSchedule', 'schedule' => $dao, 'mapping' => $dao).
16 * Ex: Array('class'=>'CRM_Mailing_BAO_MailingJob', 'mailing' => $dao).
18 * For lack of a better place, here's a list of known/intended context values:
20 * - controller: string, the class which is managing the mail-merge.
21 * - smarty: bool, whether to enable smarty support.
22 * - contactId: int, the main person/org discussed in the message.
23 * - contact: array, the main person/org discussed in the message.
24 * (Optional for performance tweaking; if omitted, will load
25 * automatically from contactId.)
26 * - actionSchedule: DAO, the rule which triggered the mailing
27 * [for CRM_Core_BAO_ActionScheduler].
32 * @var EventDispatcherInterface
34 protected $dispatcher;
38 * Each message is an array with keys:
39 * - string: Unprocessed message (eg "Hello, {display_name}.").
40 * - format: Media type (eg "text/plain").
41 * - tokens: List of tokens which are actually used in this message.
46 * DO NOT access field this directly. Use TokenRow. This is
47 * marked as public only to benefit TokenRow.
50 * Array(int $pos => array $keyValues);
55 * DO NOT access field this directly. Use TokenRow. This is
56 * marked as public only to benefit TokenRow.
59 * Ex: $rowValues[$rowPos][$format][$entity][$field] = 'something';
60 * Ex: $rowValues[3]['text/plain']['contact']['display_name'] = 'something';
65 * A list of available tokens
67 * Array(string $dottedName => array('entity'=>string, 'field'=>string, 'label'=>string)).
69 protected $tokens = NULL;
72 * A list of available tokens formatted for display
74 * Array('{' . $dottedName . '}' => 'labelString')
76 protected $listTokens = NULL;
81 * @param EventDispatcherInterface $dispatcher
82 * @param array $context
84 public function __construct($dispatcher, $context) {
85 $this->dispatcher
= $dispatcher;
86 $this->context
= $context;
90 * Register a string for which we'll need to merge in tokens.
93 * Ex: 'subject', 'body_html'.
94 * @param string $value
95 * Ex: '<p>Hello {contact.name}</p>'.
96 * @param string $format
98 * @return TokenProcessor
100 public function addMessage($name, $value, $format) {
101 $this->messages
[$name] = array(
104 'tokens' => \CRM_Utils_Token
::getTokens($value),
114 public function addRow() {
115 $key = $this->next++
;
116 $this->rowContexts
[$key] = array();
117 $this->rowValues
[$key] = array(
118 'text/plain' => array(),
119 'text/html' => array(),
122 return new TokenRow($this, $key);
126 * @param array $params
128 * - entity: string, e.g. "profile".
129 * - field: string, e.g. "viewUrl".
130 * - label: string, e.g. "Default Profile URL (View Mode)".
131 * @return TokenProcessor
133 public function addToken($params) {
134 $key = $params['entity'] . '.' . $params['field'];
135 $this->tokens
[$key] = $params;
140 * @param string $name
143 * - string: Unprocessed message (eg "Hello, {display_name}.").
144 * - format: Media type (eg "text/plain").
146 public function getMessage($name) {
147 return $this->messages
[$name];
151 * Get a list of all tokens used in registered messages.
155 public function getMessageTokens() {
157 foreach ($this->messages
as $message) {
158 $tokens = \CRM_Utils_Array
::crmArrayMerge($tokens, $message['tokens']);
160 foreach (array_keys($tokens) as $e) {
161 $tokens[$e] = array_unique($tokens[$e]);
167 public function getRow($key) {
168 return new TokenRow($this, $key);
172 * @return \Traversable<TokenRow>
174 public function getRows() {
175 return new TokenRowIterator($this, new \
ArrayIterator($this->rowContexts
));
179 * Get a list of all unique values for a given context field,
180 * whether defined at the processor or row level.
182 * @param string $field
187 public function getContextValues($field, $subfield = NULL) {
189 if (isset($this->context
[$field])) {
191 if (isset($this->context
[$field]->$subfield)) {
192 $values[] = $this->context
[$field]->$subfield;
196 $values[] = $this->context
[$field];
199 foreach ($this->getRows() as $row) {
200 if (isset($row->context
[$field])) {
202 if (isset($row->context
[$field]->$subfield)) {
203 $values[] = $row->context
[$field]->$subfield;
207 $values[] = $row->context
[$field];
211 $values = array_unique($values);
216 * Get the list of available tokens.
219 * Ex: $tokens['event'] = array('location', 'start_date', 'end_date').
221 public function getTokens() {
222 if ($this->tokens
=== NULL) {
223 $this->tokens
= array();
224 $event = new TokenRegisterEvent($this, array('entity' => 'undefined'));
225 $this->dispatcher
->dispatch(Events
::TOKEN_REGISTER
, $event);
227 return $this->tokens
;
231 * Get the list of available tokens, formatted for display
234 * Ex: $tokens[ '{token.name}' ] = "Token label"
236 public function listTokens() {
237 if ($this->listTokens
=== NULL) {
238 $this->listTokens
= array();
239 foreach ($this->getTokens() as $token => $values) {
240 $this->listTokens
['{' . $token . '}'] = $values['label'];
243 return $this->listTokens
;
247 * Compute and store token values.
249 public function evaluate() {
250 $event = new TokenValueEvent($this);
251 $this->dispatcher
->dispatch(Events
::TOKEN_EVALUATE
, $event);
258 * @param string $name
259 * The name previously registered with addMessage().
260 * @param TokenRow|int $row
261 * The object or ID for the row previously registered with addRow().
263 * Fully rendered message, with tokens merged.
265 public function render($name, $row) {
266 if (!is_object($row)) {
267 $row = $this->getRow($row);
270 $message = $this->getMessage($name);
271 $row->fill($message['format']);
272 $useSmarty = !empty($row->context
['smarty']);
274 // FIXME preg_callback.
275 $tokens = $this->rowValues
[$row->tokenRow
][$message['format']];
276 $flatTokens = array();
277 \CRM_Utils_Array
::flatten($tokens, $flatTokens, '', '.');
278 $filteredTokens = array();
279 foreach ($flatTokens as $k => $v) {
280 $filteredTokens['{' . $k . '}'] = ($useSmarty ? \CRM_Utils_Token
::tokenEscapeSmarty($v) : $v);
283 $event = new TokenRenderEvent($this);
284 $event->message
= $message;
285 $event->context
= $row->context
;
287 $event->string = strtr($message['string'], $filteredTokens);
288 $this->dispatcher
->dispatch(Events
::TOKEN_RENDER
, $event);
289 return $event->string;
294 class TokenRowIterator
extends \IteratorIterator
{
296 protected $tokenProcessor;
299 * @param TokenProcessor $tokenProcessor
300 * @param Traversable $iterator
302 public function __construct(TokenProcessor
$tokenProcessor, Traversable
$iterator) {
303 parent
::__construct($iterator); // TODO: Change the autogenerated stub
304 $this->tokenProcessor
= $tokenProcessor;
307 public function current() {
308 return new TokenRow($this->tokenProcessor
, parent
::key());