Merge pull request #17736 from civicrm/5.27
[civicrm-core.git] / ext / flexmailer / src / Listener / SimpleFilter.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11 namespace Civi\FlexMailer\Listener;
12
13 use Civi\FlexMailer\Event\ComposeBatchEvent;
14
15 /**
16 * Class SimpleFilter
17 * @package Civi\FlexMailer\Listener
18 *
19 * Provides a slightly sugary utility for writing a filter
20 * that applies to email content.
21 *
22 * Note: This class is not currently used within org.civicrm.flexmailer, but
23 * it ma ybe used by other extensions.
24 */
25 class SimpleFilter {
26
27 /**
28 * Apply a filter function to each instance of a property of an email.
29 *
30 * This variant visits each value one-by-one.
31 *
32 * @param \Civi\FlexMailer\Event\ComposeBatchEvent $e
33 * @param string $field
34 * The name of a MailParam field.
35 * @param mixed $filter
36 * Function($value, FlexMailerTask $task, ComposeBatchEvent $e).
37 * The function returns a filtered value.
38 * @throws \CRM_Core_Exception
39 * @see \CRM_Utils_Hook::alterMailParams
40 */
41 public static function byValue(ComposeBatchEvent $e, $field, $filter) {
42 foreach ($e->getTasks() as $task) {
43 /** @var \Civi\FlexMailer\FlexMailerTask $task */
44 $value = $task->getMailParam($field);
45 if ($value !== NULL) {
46 $task->setMailParam($field, call_user_func($filter, $value, $task, $e));
47 }
48 }
49 }
50
51 /**
52 * Apply a filter function to a property of all email messages.
53 *
54 * This variant visits the values as a big array. This makes it
55 * amenable to batch-mode filtering in preg_replace or preg_replace_callback.
56 *
57 * @param \Civi\FlexMailer\Event\ComposeBatchEvent $e
58 * @param string $field
59 * The name of a MailParam field.
60 * @param mixed $filter
61 * Function($values, ComposeBatchEvent $e).
62 * Return a modified list of values.
63 * @throws \CRM_Core_Exception
64 * @see \CRM_Utils_Hook::alterMailParams
65 */
66 public static function byColumn(ComposeBatchEvent $e, $field, $filter) {
67 $tasks = $e->getTasks();
68 $values = array();
69
70 foreach ($tasks as $k => $task) {
71 /** @var \Civi\FlexMailer\FlexMailerTask $task */
72 $value = $task->getMailParam($field);
73 if ($value !== NULL) {
74 $values[$k] = $value;
75 }
76 }
77
78 $values = call_user_func_array($filter, array($values, $e));
79
80 foreach ($values as $k => $value) {
81 $tasks[$k]->setMailParam($field, $value);
82 }
83 }
84
85 }