<?php
namespace Drupal\app_core\Plugin\views\filter;
use Drupal\views\Plugin\views\filter\FilterPluginBase;
/**
* Filter for recommended products.
*
* @ingroup views_filter_handlers
*
* @ViewsFilter("recommended_products")
*/
class RecommendedProductsFilter extends FilterPluginBase {
public function query() {
$this->ensureMyTable();
$product_id = $this->view->args[0];
$product = \Drupal::entityTypeManager()
->getStorage('commerce_product')
->load($product_id);
$term = $product->get('app_group')->referencedEntities()[0];
// Recommended manufacturer.
$manufacturer = \Drupal::entityTypeManager()
->getStorage('taxonomy_term')
->loadByProperties([
'vid' => 'manufacturer',
'name' => 'AZzardo',
]);
$manufacturer = reset($manufacturer);
// Get all products belonging to the same term (group)
// and recommended manufacturer.
$products = \Drupal::entityTypeManager()
->getStorage('commerce_product')
->loadByProperties([
'app_group' => $term->id(),
'app_manufacturer' => $manufacturer->id(),
]);
foreach ($products as $key => $product) {
$onDiscount = $this->checkIfOnDiscountAndOnStock($product);
if (!$onDiscount) {
unset($products[$key]);
}
}
$product_ids = [];
array_walk($products, function($product) use (&$product_ids) {
$product_ids[] = $product->id();
});
$this->query->addWhere(0, 'product_id', $product_ids, 'IN');
$mile = 'mile';
}
public function checkIfOnDiscountAndOnStock($product){
$variations = $product->getVariations();
foreach ($variations as $variation) {
if (!empty($variation->get('list_price')) && $variation->get('app_purchaseitem')->value == 1) {
if ($variation->get('list_price')->number > $variation->get('price')->number) {
return TRUE;
}
}
}
return FALSE;
}
}