summaryrefslogtreecommitdiff
path: root/www/crm/wp-content/plugins/civicrm/civicrm/ext/api4/Civi/Api4/Generic/BasicReplaceAction.php
blob: 8e0dd22e5a849ae7edccb1c1f418376bd74cd536 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php

namespace Civi\Api4\Generic;

use Civi\Api4\Generic\Result;

/**
 * Given a set of records, will appropriately update the database.
 *
 * @method $this setRecords(array $records) Array of records.
 * @method $this addRecord($record) Add a record to update.
 * @method array getRecords()
 * @method $this setReload(bool $reload) Specify whether complete objects will be returned after saving.
 * @method bool getReload()
 */
class BasicReplaceAction extends AbstractBatchAction {

  /**
   * Array of records.
   *
   * Should be in the same format as returned by Get.
   *
   * @required
   * @var array
   */
  protected $records = [];

  /**
   * Reload objects after saving.
   *
   * Setting to TRUE will load complete records and return them as the api result.
   * If FALSE the api usually returns only the fields specified to be updated.
   *
   * @var bool
   */
  protected $reload = FALSE;

  /**
   * @inheritDoc
   */
  public function _run(Result $result) {
    $items = $this->getBatchRecords();

    // Copy params from where clause if the operator is =
    $paramsFromWhere = [];
    foreach ($this->where as $clause) {
      if (is_array($clause) && $clause[1] === '=') {
        $paramsFromWhere[$clause[0]] = $clause[2];
      }
    }

    $idField = $this->getSelect()[0];
    $toDelete = array_column($items, NULL, $idField);

    foreach ($this->records as $record) {
      $record += $paramsFromWhere;
      if (!empty($record[$idField])) {
        $id = $record[$idField];
        unset($toDelete[$id], $record[$idField]);
        $result[] = civicrm_api4($this->getEntityName(), 'update', [
          'reload' => $this->reload,
          'where' => [[$idField, '=', $id]],
          'values' => $record,
        ])->first();
      }
      else {
        $result[] = civicrm_api4($this->getEntityName(), 'create', [
          'values' => $record,
        ])->first();
      }
    }

    $result->deleted = [];
    if ($toDelete) {
      $result->deleted = (array) civicrm_api4($this->getEntityName(), 'delete', [
        'where' => [[$idField, 'IN', array_keys($toDelete)]],
      ]);
    }
  }

}