<?php

/**
 * @file
 * Provides an entity type for testing definition and schema updates.
 */

use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;

/**
 * Implements hook_entity_base_field_info().
 */
function entity_test_update_entity_base_field_info(EntityTypeInterface $entity_type) {
  // Add a base field that will be used to test that fields added through
  // hook_entity_base_field_info() are handled correctly during a schema
  // conversion (e.g. from non-revisionable to revisionable).
  if ($entity_type->id() == 'entity_test_update') {
    $fields = [];
    $fields['test_entity_base_field_info'] = BaseFieldDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Field added by hook_entity_base_field_info()'))
      ->setTranslatable(TRUE)
      ->setRevisionable(TRUE);

    return $fields;
  }
}

/**
 * Implements hook_entity_field_storage_info().
 */
function entity_test_update_entity_field_storage_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'entity_test_update') {
    return \Drupal::state()->get('entity_test_update.additional_field_storage_definitions', []);
  }
}

/**
 * Implements hook_entity_type_alter().
 */
function entity_test_update_entity_type_alter(array &$entity_types) {
  // Allow entity_test_update tests to override the entity type definition.
  $entity_type = \Drupal::state()->get('entity_test_update.entity_type', $entity_types['entity_test_update']);
  if ($entity_type !== 'null') {
    $entity_types['entity_test_update'] = $entity_type;
  }
  else {
    unset($entity_types['entity_test_update']);
  }
}

/**
 * Implements hook_ENTITY_TYPE_presave() for the 'view' entity type.
 */
function entity_test_update_view_presave(EntityInterface $entity) {
  if (\Drupal::state()->get('entity_test_update.throw_view_exception') === $entity->id()) {
    throw new \LogicException('The view could not be saved.');
  }
}
