mutual_credit-5.0.x-dev/src/Plugin/Field/FieldType/WorthFieldItemList.php
src/Plugin/Field/FieldType/WorthFieldItemList.php
<?php namespace Drupal\mcapi\Plugin\Field\FieldType; use Drupal\Core\Field\FieldItemList; /** * Represents a entity worth field. */ class WorthFieldItemList extends FieldItemList { /** * {@inheritdoc} */ public function isEmpty() { $empties = []; foreach ($this->list as $item) { if (empty($item->value) && empty($item->currency->zero)) { $empties[] = $item->currency->id; } } return count($empties) == count($this->list); } /** * Get a list of currencies. * * @return array * The currencies or Currency IDs */ public function currencies() : array { $c = []; foreach ($this->list as $item) { $c[] = $item->curr_id; } return $c; } /** * {@inheritdoc} */ public function generateSampleItems($count = 1) { // We ignore the given $count, add one or maybe 2 currencies // Use 1 or maybe two of the active currencies. $currencies = \Drupal::entityTypeManager()->getStorage('mcapi_currency')->loadByProperties(['status' => TRUE]); $field_definition = $this->getFieldDefinition(); $field_type_class = \Drupal::service('plugin.manager.field.field_type')->getPluginClass($field_definition->getType()); $temp = $currencies; shuffle($temp); $currency = array_pop($temp); $field_definition->currency = $currency; $values[] = $field_type_class::generateSampleValue($field_definition); if (rand(0, 4) == 0) { if ($field_definition->currency = array_pop($temp)) { $values[] = $field_type_class::generateSampleValue($field_definition); } } $this->setValue($values); } /** * {@inheritdoc} */ public function __get($name) { if ($result = parent::__get($name)) { return $result; } foreach ($this->list as $item) { if ($item->curr_id == $name) { return $item->value; } } } public function __toString() { $vals = []; foreach ($this->list as $item) { $vals[] = (string)$item; } return implode(' | ', $vals); } /** * Formatting with all the field scaffolding. * @param int $mode * One of the DISPLAY constants on \Drupal\mcapi\Entity\CurrencyInterface * @return RenderableInterface */ public function format(int $mode = 2) : string { foreach ($this->list as $delta => $item) { $formatted[] = $item->format($mode); } return implode(', ', $formatted); } }