Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
RelationshipContactsItemList
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
3 / 3
12
100.00% covered (success)
100.00%
1 / 1
 computeValue
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 setValue
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
5
 referencedEntities
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2
3declare(strict_types=1);
4
5namespace Drupal\crm\Field;
6
7use Drupal\Core\TypedData\ComputedItemListTrait;
8use Drupal\Core\Field\FieldItemList;
9use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
10
11/**
12 * Computed field for the contact in a relationship.
13 */
14class RelationshipContactsItemList extends FieldItemList implements EntityReferenceFieldItemListInterface {
15  use ComputedItemListTrait;
16
17  /**
18   * {@inheritdoc}
19   */
20  protected function computeValue() {
21    $field_name = $this->getName();
22    $entity = $this->getEntity();
23
24    $contacts = $entity->get('contacts')->getValue();
25    $contact = NULL;
26
27    if (!empty($contacts)) {
28
29      $contact = $contacts[0]['target_id'] ?? NULL;
30      if ($field_name === 'contact_b') {
31        $contact = $contacts[1]['target_id'] ?? NULL;
32      }
33    }
34
35    $this->list[0] = $this->createItem(0, ['target_id' => $contact]);
36  }
37
38  /**
39   * {@inheritdoc}
40   */
41  public function setValue($values, $notify = TRUE) {
42
43    if (!empty($values)) {
44      $field_name = $this->getName();
45      $entity = $this->getEntity();
46      $contacts_field = $entity->get('contacts');
47
48      // Get current contacts.
49      $contacts = $contacts_field->getValue();
50
51      // Determine which contact to update based on field name.
52      $contact_index = ($field_name === 'contact_b') ? 1 : 0;
53
54      // Ensure we have enough contacts in the array.
55      while (count($contacts) <= $contact_index) {
56        $contacts[] = ['target_id' => NULL];
57      }
58
59      // Update the appropriate contact.
60      $contacts[$contact_index]['target_id'] = is_array($values) ? $values[0]['target_id'] : $values;
61
62      // Set the updated contacts field.
63      $contacts_field->setValue($contacts);
64    }
65
66    // Call parent to maintain normal field behavior.
67    parent::setValue($values, $notify);
68  }
69
70  /**
71   * {@inheritdoc}
72   */
73  public function referencedEntities() {
74    $field_name = $this->getName();
75    $entities = $this->getEntity()->get('contacts')->referencedEntities();
76
77    if ($field_name === 'contact_b') {
78      return isset($entities[1]) ? [$entities[1]] : [];
79    }
80
81    return isset($entities[0]) ? [$entities[0]] : [];
82  }
83
84}