StockLocationStorage.php in Commerce Stock 8
File
modules/local_storage/src/StockLocationStorage.php
View source
<?php
namespace Drupal\commerce_stock_local;
use Drupal\commerce\CommerceContentEntityStorage;
use Drupal\commerce\PurchasableEntityInterface;
use Drupal\commerce_stock_local\Event\FilterLocationsEvent;
use Drupal\commerce_stock_local\Event\LocalStockEvents;
use Drupal\commerce\Context;
class StockLocationStorage extends CommerceContentEntityStorage implements StockLocationStorageInterface {
public function loadEnabled(PurchasableEntityInterface $entity) {
$query = $this
->getQuery()
->condition('status', TRUE);
$result = $query
->execute();
if (empty($result)) {
return [];
}
$enabled_locations = $this
->loadMultiple($result);
$event = new FilterLocationsEvent($entity, $enabled_locations);
$this->eventDispatcher
->dispatch(LocalStockEvents::FILTER_STOCK_LOCATIONS, $event);
$enabled_locations = $event
->getLocations();
return $enabled_locations;
}
public function loadInContext(Context $context, PurchasableEntityInterface $entity) {
$store = $context
->getStore();
if ($store
->hasField('field_available_stock_locations')) {
$locations = $store->field_available_stock_locations
->getValue();
if (empty($locations)) {
return $this
->loadEnabled($entity);
}
$store_locations = [];
foreach ($locations as $location) {
$store_locations[$location['target_id']] = $location['target_id'];
}
$store_locations = $this
->loadMultiple($store_locations);
foreach ($store_locations as $id => $location) {
if (!$location
->isActive()) {
unset($store_locations[$id]);
}
}
if (empty($locations)) {
return $this
->loadEnabled($entity);
}
return $store_locations;
}
else {
return $this
->loadEnabled($entity);
}
}
public function getTransactionLocation(Context $context, PurchasableEntityInterface $entity) {
$store = $context
->getStore();
if ($store
->hasField('field_stock_allocation_location')) {
$locations = $store->field_stock_allocation_location
->getValue();
if (empty($locations)) {
$locations = $this
->loadInContext($context, $entity);
return empty($locations) ? NULL : array_shift($locations);
}
else {
$location_id = array_shift($locations)['target_id'];
$store_location = $this
->load($location_id);
return $store_location;
}
}
else {
$locations = $this
->loadInContext($context, $entity);
return empty($locations) ? NULL : array_shift($locations);
}
}
}