InvoiceOrderAccessCheck.php in Commerce Invoice 8.2
File
src/Access/InvoiceOrderAccessCheck.php
View source
<?php
namespace Drupal\commerce_invoice\Access;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\Routing\Route;
class InvoiceOrderAccessCheck implements AccessInterface {
protected $entityTypeManager;
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account) {
$invoice_type_storage = $this->entityTypeManager
->getStorage('commerce_invoice_type');
$order = $route_match
->getParameter('commerce_order');
$invoice_type = $route_match
->getParameter('commerce_invoice_type') ?: $invoice_type_storage
->load('default');
$access = AccessResult::allowedIfHasPermission($account, 'administer commerce_invoice')
->mergeCacheMaxAge(0);
if ($route
->hasRequirement('_invoice_generate_form_access')) {
$disallowed_order_states = [
'draft',
];
if ($invoice_type
->id() !== 'credit_memo') {
$disallowed_order_states[] = 'canceled';
}
if (in_array($order
->getState()
->getId(), $disallowed_order_states, TRUE) || !$order
->getTotalPrice()) {
return AccessResult::forbidden()
->mergeCacheMaxAge(0);
}
$result = $this->entityTypeManager
->getStorage('commerce_invoice')
->getAggregateQuery()
->condition('type', $invoice_type
->id(), '=')
->condition('orders', [
$order
->id(),
], 'IN')
->conditionAggregate('total_price.number', 'SUM', $order
->getTotalPrice()
->getNumber(), '>=')
->accessCheck(FALSE)
->execute();
if (!empty($result)) {
return AccessResult::forbidden()
->mergeCacheMaxAge(0);
}
$order_requirements = !empty($order
->getStoreId());
$access
->andIf(AccessResult::allowedIf($order_requirements));
}
return $access;
}
}