cache_entity_type-1.x-dev/src/Entity/ExtendedCacheEntityBase.php

src/Entity/ExtendedCacheEntityBase.php
<?php

declare(strict_types=1);

namespace Drupal\cache_entity_type\Entity;

use Drupal\cache_entity_type\Exception\RequiredEntityPropertiesMissingException;

/**
 * Provides additional utilities on top of the CacheEntityBase.
 *
 * @package Drupal\cache_entity_type\Entity
 */
abstract class ExtendedCacheEntityBase extends CacheEntityBase {

  /**
   * The constructor value keys of properties that must be set on object creation.
   */
  protected const REQUIRED_PROPERTIES = [];

  /**
   * Checks if all required values are set.
   *
   * @param array $values
   *   The values to be used for creating a new object.
   *
   * @return bool
   *   TRUE or FALSE.
   */
  protected function areRequiredValuesSet(array $values): bool {
    foreach (static::REQUIRED_PROPERTIES as $requiredPropertyKey) {
      if (!isset($values[$requiredPropertyKey])) {
        return FALSE;
      }
    }

    return TRUE;
  }

  /**
   * ExtendedCacheEntityBase constructor.
   *
   * @param array $values
   *   An array of values to set,
   *   keyed by property name.
   *   Must contain properties for keys
   *   defined in static::REQUIRED_PROPERTIES.
   * @param string $entity_type
   *   The entity type ID.
   *
   * @throws \Drupal\cache_entity_type\Exception\RequiredEntityPropertiesMissingException
   *   Thrown if required entity properties are not set.
   */
  public function __construct(array $values, $entity_type) {
    /* We don't want to set object properties 2 times.
    So we're passing empty property values to the parent.
    We still want to set the id though.
    @see \Drupal\Core\Entity\EntityBase::__construct() */
    $parentValues = [];
    if (isset($values[static::ID_KEY])) {
      $parentValues[static::ID_KEY] = $values[static::ID_KEY];
    }
    parent::__construct($parentValues, $entity_type);

    if (!$this->areRequiredValuesSet($values)) {
      throw new RequiredEntityPropertiesMissingException($entity_type, $values);
    }
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc