xtcentity-2.x-dev/src/Plugin/Field/FieldFormatter/XtcFieldPluginWordpress.php

src/Plugin/Field/FieldFormatter/XtcFieldPluginWordpress.php
<?php

namespace Drupal\xtcentity\Plugin\Field\FieldFormatter;

use Drupal\Component\Serialization\Json;
use Drupal\Core\Entity\EntityFieldManager;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Url;
use Drupal\field\Entity\FieldConfig;
use Drupal\xtc\XtendedContent\API\XtcLoaderHandler;
use Drupal\xtc\XtendedContent\API\XtcLoaderProfile;
use Drupal\xtcprofile\Entity\XtcProfile;

/**
 * Plugin implementation of the 'xtcfield_plugin_html_formatter' formatter.
 *
 * @FieldFormatter(
 *   id = "xtcfield_plugin_wordpress_formatter",
 *   label = @Translation("WordPress"),
 *   field_types = {
 *     "xtcfield_plugin_profile",
 *   },
 *   quickedit = {
 *     "editor" = "plain_text"
 *   }
 * )
 */
class XtcFieldPluginWordpress extends FormatterBase implements ContainerFactoryPluginInterface {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    foreach ($items as $delta => $item) {
      $elements[$delta] = [
        '#theme' => $this->getSetting('theme'),
        '#response' => $this->viewValue($item),
      ];
    }
    return $elements;
  }

  /**
   * Generate the output appropriate for one field item.
   *
   * @param \Drupal\Core\Field\FieldItemInterface $item
   *
   * @return array
   */
  protected function viewValue(FieldItemInterface $item) {
    $urlId = \Drupal::request()->get('id');
    if(!empty($urlId)) {
      $options = ['query' => $urlId];
    }
    elseif(!empty($this->getSetting('id_field'))) {
      $id = $item->getEntity()->get($this->getSetting('id_field'))->getString();
      $options = ['query' => $id];
    }
    $loaded = false;
    $name = $item->getString();
    $content = [];

    try {
      $test = XtcLoaderProfile::load($name);
      $loaded = true;
    } finally {
      if($loaded) {
        $profile = XtcLoaderProfile::content($name, $options);
        $response = Json::decode($profile);
        $content['body'] = static::getResponseContent($name, $response);
        return $content;
      }
      $xtcprofile = XtcProfile::load($name);
      $newprofile = $options = $xtcprofile->get('options');
      $newprofile['label'] = $xtcprofile->label();
      $newprofile['id'] = $xtcprofile->id();

      $handler = XtcLoaderHandler::get($options['handler']);
      $handler->setProfile($newprofile)
        ->setOptions($options);

      $content['body'] = $xtcprofile->get('options');
      return $content;
    }

  }

  /**
   * @param array $response
   *
   * @return string
   */
  protected static function getResponseContent($profile, array $response) {
    $body = '';
    if(empty($response[0])) {
      $body .= "<h2>" . $response['title']['rendered'] . "</h2>\n";
      $body .= $response['content']['rendered'] ?? '';
      return $body;
    }
    if (count($response) > 1) {
      foreach ($response as $key => $value) {
        $url = Url::fromRoute('xtcentity.content', ['profile' => $profile, 'id' => $value['id']]);
        $body .= '<h2><a href="' . $url->toString() . '">' . $value['title']['rendered'] . '</a></h2>' . "\n";
        $body .= $value['excerpt']['rendered'] . "\n";
      }
      return $body;
    }
    $body .= "<h2>" . $response[0]['title']['rendered'] . "</h2>\n";
    $body .= $response[0]['content']['rendered'] ?? '';
    return $body;
  }

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
        'id_field' => '',
        'theme' => '',
      ] + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state): array {
    $elements = parent::settingsForm($form, $form_state);
    $settings = $this->getSettings();

    $idOptions = ['' => ''];
    $entityFieldManager = \Drupal::service('entity_field.manager');
    $fields = $entityFieldManager->getFieldDefinitions($form['#entity_type'], $form['#bundle']);
    foreach ($fields as $name => $field) {
      if($field instanceof FieldConfig && 'integer' == $field->getType()) {
        $idOptions[$name] = $field->label();
      }
    }
    $elements['id_field'] = [
      '#type' => 'select',
      '#title' => t('ID field'),
      '#options' => $idOptions,
      '#description' => t('The ID field that can be used to query the WP content.'),
      '#default_value' => $settings['id_field'],
    ];

    $registry = theme_get_registry();
    $themeOptions = [];
    foreach ($registry as $key => $option) {
      $themeOptions[$key] = $key;
    }
    $elements['theme'] = [
      '#type' => 'select',
      '#title' => t('Theme function'),
      '#options' => $themeOptions,
      '#description' => t('The theme functions that can be used to display the results.'),
      '#default_value' => $settings['theme'],
    ];

    return $elements;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = [];

    $settings = $this->getSettings();

    if (!empty($settings['id_field'])) {
      $summary[] = t('ID field: @id_field', ['@id_field' => $settings['id_field']]);
    }
    else {
      $summary[] = t('No ID field is defined.');
    }

    if (!empty($settings['theme'])) {
      $summary[] = t('Theme function: @theme', ['@theme' => $settings['theme']]);
    }
    else {
      $summary[] = t('No Theme functions is defined.');
    }

    return $summary;
  }

}

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

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