fox-1.1.2/src/Plugin/FoxCommand/FoxCommandCreate.php

src/Plugin/FoxCommand/FoxCommandCreate.php
<?php

namespace Drupal\fox\Plugin\FoxCommand;

use Drupal\fox\FoxCommandsHelper as Helper;

/**
 * CREATE fox command.
 *
 * @FoxCommand(
 *   id = "create",
 *   label = @Translation("Entity creation. Usage: CREATE id,label.")
 * )
 */
class FoxCommandCreate extends FoxCommandBaseClass {

  /**
   * {@inheritdoc}
   */
  public function execute(array $params, array $variables, array $options): array {
    $entity_type = $variables['entity_type'] ?? NULL;
    if (empty($entity_type)) {
      return $this->errorReturn($this->t('Empty entity type. Use USE command.'));
    }
    $bundle = $variables['bundle'] ?? NULL;

    $bad_params = empty($params);
    if (!$bad_params) {
      $items = Helper::prepareParameters($params);
      $bad_params = count($items) < 2;
    }
    if ($bad_params) {
      return $this->errorReturn($this->t('Usage: CREATE id,label.'));
    }
    [$id, $label] = $items;

    $helper = $this->foxCommandsHelper();

    $id_key = $helper->entityKey($entity_type, 'id');
    $label_key = $helper->entityKey($entity_type, 'label');
    if (empty($id_key) || empty($label_key)) {
      return $this->errorReturn($this->t('Empty ID and/or label entity key.'));
    }
    $entity_param = [
      $id_key => $id,
      $label_key => $label,
    ];

    if (!empty($bundle)) {
      $bundle_key = $helper->entityKey($entity_type, 'bundle');
      if (!empty($bundle_key)) {
        $entity_param[$bundle_key] = $bundle;
      }
    }

    try {
      $entity = $helper->entityTypeManager()
        ->getStorage($entity_type)
        ->create($entity_param);
      $entity->save();
    }
    catch (\Exception $e) {
      return $this->errorReturn($e->getMessage());
    }

    return [
      'message' => $this->t('Entity was created'),
    ];
  }

}

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

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