/**
* Add a row of data.
*
+ * @param array|NULL $context
+ * Optionally, initialize the context for this row.
+ * Ex: ['contact_id' => 123].
* @return TokenRow
*/
- public function addRow() {
+ public function addRow($context = NULL) {
$key = $this->next++;
$this->rowContexts[$key] = [];
$this->rowValues[$key] = [
'text/html' => [],
];
- return new TokenRow($this, $key);
+ $row = new TokenRow($this, $key);
+ if ($context !== NULL) {
+ $row->context($context);
+ }
+ return $row;
+ }
+
+ /**
+ * Add several rows.
+ *
+ * @param array $contexts
+ * List of rows to add.
+ * Ex: [['contact_id'=>123], ['contact_id'=>456]]
+ * @return TokenRow[]
+ * List of row objects
+ */
+ public function addRows($contexts) {
+ $rows = [];
+ foreach ($contexts as $context) {
+ $row = $this->addRow($context);
+ $rows[$row->tokenRow] = $row;
+ }
+ return $rows;
}
/**
];
}
+ /**
+ * Test that a row can be added via "addRow(array $context)".
+ */
+ public function testAddRow() {
+ $p = new TokenProcessor($this->dispatcher, [
+ 'controller' => __CLASS__,
+ ]);
+ $createdRow = $p->addRow(['one' => 'Apple'])
+ ->context('two', 'Banana');
+ $gotRow = $p->getRow(0);
+ foreach ([$createdRow, $gotRow] as $row) {
+ $this->assertEquals('Apple', $row->context['one']);
+ $this->assertEquals('Banana', $row->context['two']);
+ }
+ }
+
+ /**
+ * Test that multiple rows can be added via "addRows(array $contexts)".
+ */
+ public function testAddRows() {
+ $p = new TokenProcessor($this->dispatcher, [
+ 'controller' => __CLASS__,
+ ]);
+ $createdRows = $p->addRows([
+ ['one' => 'Apple', 'two' => 'Banana'],
+ ['one' => 'Pomme', 'two' => 'Banane'],
+ ]);
+ $gotRow0 = $p->getRow(0);
+ foreach ([$createdRows[0], $gotRow0] as $row) {
+ $this->assertEquals('Apple', $row->context['one']);
+ $this->assertEquals('Banana', $row->context['two']);
+ }
+ $gotRow1 = $p->getRow(1);
+ foreach ([$createdRows[1], $gotRow1] as $row) {
+ $this->assertEquals('Pomme', $row->context['one']);
+ $this->assertEquals('Banane', $row->context['two']);
+ }
+ }
+
/**
* Check that the TokenRow helper can correctly read/update context
* values.