OnlySpecialOffer.php

PHOTO EMBED

Tue Jul 26 2022 12:41:49 GMT+0000 (Coordinated Universal Time)

Saved by @igor #drupal #mysql

<?php

declare(strict_types = 1);

namespace Drupal\enmon_core\Plugin\search_api\processor;

use Drupal\search_api\Datasource\DatasourceInterface;
use Drupal\search_api\IndexInterface;
use Drupal\search_api\Item\ItemInterface;
use Drupal\search_api\Processor\ProcessorPluginBase;
use Drupal\search_api\Processor\ProcessorProperty;

/**
 * @SearchApiProcessor(
 *   id = "only_special_offer",
 *   label = @Translation("Only special offer"),
 *   description = @Translation("Calculates whether the only special offer is true on all variation"),
 *   stages = {
 *     "add_properties" = 0,
 *   },
 * )
 */
class OnlySpecialOffer extends ProcessorPluginBase {

  /**
   * {@inheritdoc}
   */
  public static function supportsIndex(IndexInterface $index) {
    $supported_entity_types = ['commerce_product'];
    foreach ($index->getDatasources() as $datasource) {
      if (in_array($datasource->getEntityTypeId(), $supported_entity_types)) {
        return TRUE;
      }
    }

    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function getPropertyDefinitions(DatasourceInterface $datasource = NULL) {
    $properties = [];

    if (!$datasource) {
      $definition = [
        'label' => $this->t('Only special offers'),
        'description' => $this->t('Whether the product all variation marked with only special offer'),
        'type' => 'boolean',
        'is_list' => TRUE,
        'processor_id' => $this->getPluginId(),
      ];
      $properties['only_special_offers'] = new ProcessorProperty($definition);
    }

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public function addFieldValues(ItemInterface $item) {
    $fields = $item->getFields();

    $only_special_offer_fields = $this->getFieldsHelper()
      ->filterForPropertyPath($fields, NULL, 'only_special_offers');

    /** @var \Drupal\Core\Entity\Plugin\DataType\EntityAdapter $entity_adapter */
    $entity_adapter = $item->getOriginalObject();

    /** @var \Drupal\commerce_product\Entity\Product $product */
    $product = $entity_adapter->getEntity();

    /** @var \Drupal\commerce_product\Entity\ProductVariationInterface $product_variation */
    foreach ($product->getVariations() as $product_variation) {
      $is_only_special_offer = $product_variation->get('field_only_special_offer')->value;

      foreach ($only_special_offer_fields as $only_special_offer_field) {
        $only_special_offer_field->addValue($is_only_special_offer);
      }
    }
  }

}
content_copyCOPY

Processor for Search API.