page_tester-1.0.x-dev/src/Entity/Test.php

src/Entity/Test.php
<?php

declare(strict_types=1);

namespace Drupal\page_tester\Entity;

use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\page_tester\TestInterface;
use Drupal\user\EntityOwnerTrait;

/**
 * Defines the test entity class.
 *
 * @ContentEntityType(
 *   id = "page_tester_test",
 *   label = @Translation("Test"),
 *   label_collection = @Translation("Tests"),
 *   label_singular = @Translation("test"),
 *   label_plural = @Translation("tests"),
 *   label_count = @PluralTranslation(
 *     singular = "@count tests",
 *     plural = "@count tests",
 *   ),
 *   handlers = {
 *     "list_builder" = "Drupal\page_tester\TestListBuilder",
 *     "views_data" = "Drupal\views\EntityViewsData",
 *     "form" = {
 *       "add" = "Drupal\page_tester\Form\TestForm",
 *       "edit" = "Drupal\page_tester\Form\TestForm",
 *       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
 *       "delete-multiple-confirm" = "Drupal\Core\Entity\Form\DeleteMultipleForm",
 *     },
 *     "route_provider" = {
 *       "html" = "Drupal\page_tester\Routing\TestHtmlRouteProvider",
 *     },
 *   },
 *   base_table = "page_tester_test",
 *   data_table = "page_tester_test_field_data",
 *   translatable = TRUE,
 *   admin_permission = "administer page_tester_test",
 *   entity_keys = {
 *     "id" = "id",
 *     "langcode" = "langcode",
 *     "label" = "label",
 *     "uuid" = "uuid",
 *     "owner" = "uid",
 *   },
 *   links = {
 *     "collection" = "/admin/content/test",
 *     "add-form" = "/test/add",
 *     "canonical" = "/test/{page_tester_test}",
 *     "edit-form" = "/test/{page_tester_test}",
 *     "delete-form" = "/test/{page_tester_test}/delete",
 *     "delete-multiple-form" = "/admin/content/test/delete-multiple",
 *   },
 * )
 */
final class Test extends ContentEntityBase implements TestInterface {

  use EntityChangedTrait;
  use EntityOwnerTrait;

  /**
   * Helper function to populate all menus.
   *
   * @return array
   *   Dropdown options.
   */
  public static function getAllMenus() {
    $allMenus = [];
    $menu_storage = \Drupal::entityTypeManager()->getStorage('menu');
    $menus = $menu_storage->loadMultiple();
    foreach ($menus as $menu_id => $menu) {
      $allMenus[$menu_id] = $menu->label();
    }
    return $allMenus;
  }

  /**
   * Helper function to populate all content types.
   *
   * @return array
   *   Dropdown options.
   */
  public static function getAllContentTypes() {
    $contentTypes = [];
    $content_types = \Drupal::entityTypeManager()
      ->getStorage('node_type')
      ->loadMultiple();
    foreach ($content_types as $type => $definition) {
      $contentTypes[$type] = $definition->label();
    }

    return $contentTypes;
  }


  /**
   * Helper function to populate all vocabularies.
   *
   * @return array
   *   Dropdown options.
   */
  public static function getAllVocabularies() {
    $taxonomies = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_vocabulary')
      ->loadMultiple();
    $vocabularies = [];
    foreach ($taxonomies as $entityTypeId => $entityType) {
      /** @var string $entityTypeId */
      $name = ucfirst(implode(" ", explode("_", $entityTypeId)));
      $vocabularies[$entityTypeId] = $name;
    }
    return $vocabularies;
  }

  /**
   * Helper function to populate the tests list.
   *
   * @return array
   *   Dropdown options.
   */
  public static function getTests() {
    $tests = [];
    $testManager = \Drupal::service('plugin.manager.tests');
    $plugin_definitions = $testManager->getDefinitions();
    foreach ($plugin_definitions as $plugin_id => $definition) {
      $tests[$plugin_id] = (string) $definition["label"];
    }
    return $tests;
  }

  /**
   * Helper function to populate the resource to use.
   *
   * @return array
   *   Dropdown options.
   */
  public static function getResources() {
    $resources = [];
    $moduleHandler = \Drupal::service('module_handler');
    if($moduleHandler->moduleExists('data_resource')) {
      $entityTypeManager = \Drupal::service('entity_type.manager');
      if($entityTypeManager->hasDefinition('data_resource_resource')) {
        try {
          $data_resource_resource = $entityTypeManager->getStorage('data_resource_resource');
          $nodes = $data_resource_resource->loadMultiple();
          foreach ($nodes as $node) {
            $resources[$node->id()] = $node->label();
          }
        } catch (\Drupal\Core\Database\DatabaseExceptionWrapper $e) {
          \Drupal::service('messenger')->addMessage(t('Data Resource module not installed.'));
        }
      }
    }

    return $resources;
  }

  /**
   * Returns allowed field values for the 'vocabulary_fields' field based on
   * the selected vocabulary.
   */
  public static function getAllVocabularyFields() {
    $options = [];
    foreach (self::getAllVocabularies() as $vocabulary_id => $label) {
      $fields = \Drupal::service('page_tester.field_definition_service')->getVocabularyFields($vocabulary_id);
      if (count($fields) > 0) {
        foreach ($fields as $field) {
          $options[$field] = $field;
        }
      }
    }
    return $options;
  }

  /**
   * Returns all links for the 'content_type_links' field.
   */
  public static function getAllContentTypeLinks() {
    $options = [];
    foreach (self::getAllContentTypes() as $content_type_id => $label) {
      array_push($options, \Drupal::service('page_tester.field_definition_service')->getContentTypeLinks($content_type_id));
    }
    return $options;
  }

  /**
   * Returns all links for the 'menu_links' field.
   */
  public static function getAllMenuLinks() {
    $options = [];
    foreach (self::getAllMenus() as $menue_id => $label) {
      array_push($options, \Drupal::service('page_tester.field_definition_service')->getMenuLinks($menue_id));
    }
    return $options;
  }


  /**
   * {@inheritdoc}
   */
  public function preSave(EntityStorageInterface $storage): void {
    parent::preSave($storage);
    if (!$this->getOwnerId()) {
      // If no owner has been set explicitly, make the anonymous user the owner.
      $this->setOwnerId(0);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type): array {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['label'] = BaseFieldDefinition::create('string')
      ->setTranslatable(TRUE)
      ->setLabel(t('Label'))
      ->setRequired(TRUE)
      ->setSetting('max_length', 255)
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -5,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'string',
        'weight' => -5,
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['test'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Test Plugin'))
      ->setDescription(t('Choose the test to run.'))
      ->setRevisionable(TRUE)
      ->setSettings([
        'allowed_values' => self::getTests(),
      ])
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'string',
        'weight' => 1,
      ])
      ->setDisplayOptions('form', [
        'type' => 'options_select',
        'weight' => 1,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE)
      ->setRequired(TRUE);

    $fields['vocabulary'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Vocabulary'))
      ->setDescription(t('Choose the vocabulary to test.'))
      ->setRevisionable(TRUE)
      ->setSettings([
        'allowed_values' => self::getAllVocabularies(),
      ])
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'string',
        'weight' => 1,
      ])
      ->setDisplayOptions('form', [
        'type' => 'options_select',
        'weight' => 1,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['vocabulary_fields'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Vocabulary Fields'))
      ->setDescription(t('You will need to create some form of data arrays, json, etc. Choose the fields you will add in the data.'))
      ->setRevisionable(TRUE)
      ->setCardinality(-1)
      ->setSettings([
        'allowed_values_function' => ['\Drupal\page_tester\Entity\Test', 'getAllVocabularyFields'],
      ])
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'string',
        'weight' => 1,
      ])
      ->setDisplayOptions('form', [
        'type' => 'options_buttons',
        'weight' => 1,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['content_type'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Content Type'))
      ->setDescription(t('Choose the content type to test.'))
      ->setRevisionable(TRUE)
      ->setSettings([
        'allowed_values' => self::getAllContentTypes(),
      ])
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'string',
        'weight' => 1,
      ])
      ->setDisplayOptions('form', [
        'type' => 'options_select',
        'weight' => 1,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['content_type_links'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Content Type Links'))
      ->setDescription(t('Select the links to test.'))
      ->setRevisionable(TRUE)
      ->setCardinality(-1)
      ->setSettings([
        'allowed_values_function' => ['\Drupal\page_tester\Entity\Test', 'getAllContentTypeLinks'],
      ])
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'string',
        'weight' => 1,
      ])
      ->setDisplayOptions('form', [
        'type' => 'options_buttons',
        'weight' => 1,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['menu'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Menu'))
      ->setDescription(t('Choose the menu to test.'))
      ->setRevisionable(TRUE)
      ->setSettings([
        'allowed_values' => self::getAllMenus(),
      ])
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'string',
        'weight' => 1,
      ])
      ->setDisplayOptions('form', [
        'type' => 'options_select',
        'weight' => 1,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['menu_links'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Menu Links'))
      ->setDescription(t('Select the links to test.'))
      ->setRevisionable(TRUE)
      ->setCardinality(-1)
      ->setSettings([
        'allowed_values_function' => ['\Drupal\page_tester\Entity\Test', 'getAllMenuLinks'],
      ])
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'string',
        'weight' => 1,
      ])
      ->setDisplayOptions('form', [
        'type' => 'options_buttons',
        'weight' => 1,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['resource'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Resource Plugin'))
      ->setDescription(t('Choose the resource to use.'))
      ->setRevisionable(TRUE)
      ->setSettings([
        'allowed_values' => self::getResources(),
      ])
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'string',
        'weight' => 1,
      ])
      ->setDisplayOptions('form', [
        'type' => 'options_select',
        'weight' => 1,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['status'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Status'))
      ->setDefaultValue(TRUE)
      ->setSetting('on_label', 'Enabled')
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'settings' => [
          'display_label' => FALSE,
        ],
        'weight' => 0,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'type' => 'boolean',
        'label' => 'above',
        'weight' => 0,
        'settings' => [
          'format' => 'enabled-disabled',
        ],
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['description'] = BaseFieldDefinition::create('text_long')
      ->setTranslatable(TRUE)
      ->setLabel(t('Description'))
      ->setDisplayOptions('form', [
        'type' => 'text_textarea',
        'weight' => 10,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'type' => 'text_default',
        'label' => 'above',
        'weight' => 10,
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['uid'] = BaseFieldDefinition::create('entity_reference')
      ->setTranslatable(TRUE)
      ->setLabel(t('Author'))
      ->setSetting('target_type', 'user')
      ->setDefaultValueCallback(self::class . '::getDefaultEntityOwner')
      ->setDisplayOptions('form', [
        'type' => 'entity_reference_autocomplete',
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => 60,
          'placeholder' => '',
        ],
        'weight' => 15,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'author',
        'weight' => 15,
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Authored on'))
      ->setTranslatable(TRUE)
      ->setDescription(t('The time that the test was created.'))
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'timestamp',
        'weight' => 20,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('form', [
        'type' => 'datetime_timestamp',
        'weight' => 20,
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
      ->setTranslatable(TRUE)
      ->setDescription(t('The time that the test was last edited.'));

    return $fields;
  }

}

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

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