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].
28 * - schema: array, a list of fields that will be provided for each row.
29 * This is automatically populated with any general context
30 * keys, but you may need to add extra keys for token-row data.
31 * ex: ['contactId', 'activityId'].
36 * @var EventDispatcherInterface
38 protected $dispatcher;
42 * Each message is an array with keys:
43 * - string: Unprocessed message (eg "Hello, {display_name}.").
44 * - format: Media type (eg "text/plain").
45 * - tokens: List of tokens which are actually used in this message.
50 * DO NOT access field this directly. Use TokenRow. This is
51 * marked as public only to benefit TokenRow.
54 * Array(int $pos => array $keyValues);
59 * DO NOT access field this directly. Use TokenRow. This is
60 * marked as public only to benefit TokenRow.
63 * Ex: $rowValues[$rowPos][$format][$entity][$field] = 'something';
64 * Ex: $rowValues[3]['text/plain']['contact']['display_name'] = 'something';
69 * A list of available tokens
71 * Array(string $dottedName => array('entity'=>string, 'field'=>string, 'label'=>string)).
73 protected $tokens = NULL;
78 * @param EventDispatcherInterface $dispatcher
79 * @param array $context
81 public function __construct($dispatcher, $context) {
82 $context['schema'] = isset($context['schema'])
83 ?
array_unique(array_merge($context['schema'], array_keys($context)))
84 : array_keys($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 * Compute and store token values.
233 public function evaluate() {
234 $event = new TokenValueEvent($this);
235 $this->dispatcher
->dispatch(Events
::TOKEN_EVALUATE
, $event);
242 * @param string $name
243 * The name previously registered with addMessage().
244 * @param TokenRow|int $row
245 * The object or ID for the row previously registered with addRow().
247 * Fully rendered message, with tokens merged.
249 public function render($name, $row) {
250 if (!is_object($row)) {
251 $row = $this->getRow($row);
254 $message = $this->getMessage($name);
255 $row->fill($message['format']);
256 $useSmarty = !empty($row->context
['smarty']);
258 // FIXME preg_callback.
259 $tokens = $this->rowValues
[$row->tokenRow
][$message['format']];
260 $flatTokens = array();
261 \CRM_Utils_Array
::flatten($tokens, $flatTokens, '', '.');
262 $filteredTokens = array();
263 foreach ($flatTokens as $k => $v) {
264 $filteredTokens['{' . $k . '}'] = ($useSmarty ? \CRM_Utils_Token
::tokenEscapeSmarty($v) : $v);
267 $event = new TokenRenderEvent($this);
268 $event->message
= $message;
269 $event->context
= $row->context
;
271 $event->string = strtr($message['string'], $filteredTokens);
272 $this->dispatcher
->dispatch(Events
::TOKEN_RENDER
, $event);
273 return $event->string;
278 class TokenRowIterator
extends \IteratorIterator
{
280 protected $tokenProcessor;
283 * @param TokenProcessor $tokenProcessor
284 * @param Traversable $iterator
286 public function __construct(TokenProcessor
$tokenProcessor, Traversable
$iterator) {
287 parent
::__construct($iterator); // TODO: Change the autogenerated stub
288 $this->tokenProcessor
= $tokenProcessor;
291 public function current() {
292 return new TokenRow($this->tokenProcessor
, parent
::key());