1<?php
2
3namespace Drupal\Core\Field;
4
5use Drupal\Core\Action\ActionBase;
6use Drupal\Core\Session\AccountInterface;
7
8/**
9 * Provides a base for action plugins that update one or more fields.
10 *
11 * Example implementation:
12 *
13 * @code
14 * class PromoteAndMakeSticky extends FieldUpdateActionBase {
15 *
16 *   protected function getFieldsToUpdate() {
17 *     return [
18 *       'status' => NODE_PROMOTED,
19 *       'sticky' => NODE_STICKY,
20 *     ];
21 *   }
22 *
23 * }
24 * @endcode
25 *
26 * @see \Drupal\node\Plugin\Action\PublishNode
27 */
28abstract class FieldUpdateActionBase extends ActionBase {
29
30  /**
31   * Gets an array of values to be set.
32   *
33   * @return array
34   *   Array of values with field names as keys.
35   */
36  abstract protected function getFieldsToUpdate();
37
38  /**
39   * {@inheritdoc}
40   */
41  public function execute($entity = NULL) {
42    foreach ($this->getFieldsToUpdate() as $field => $value) {
43      $entity->$field = $value;
44    }
45    $entity->save();
46  }
47
48  /**
49   * {@inheritdoc}
50   */
51  public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
52    /** @var \Drupal\Core\Access\AccessResultInterface $result */
53    $result = $object->access('update', $account, TRUE);
54
55    foreach ($this->getFieldsToUpdate() as $field => $value) {
56      $result->andIf($object->{$field}->access('edit', $account, TRUE));
57    }
58
59    return $return_as_object ? $result : $result->isAllowed();
60  }
61
62}
63