clean install

This commit is contained in:
2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 changed files with 3555714 additions and 0 deletions

View File

@@ -0,0 +1,65 @@
<?php
namespace Drupal\consumers;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityAccessControlHandler;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
/**
* Access controller for the Access Token entity.
*
* @see \Drupal\consumers\Entity\Consumer.
*/
class AccessControlHandler extends EntityAccessControlHandler {
/**
* The entity id.
*
* @var string
*/
public static $name = 'consumer';
/**
* {@inheritdoc}
*/
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
/** @var \Drupal\consumers\Entity\ConsumerInterface $entity */
$admin_permission = $this->entityType->getAdminPermission();
if ($account->hasPermission($admin_permission)) {
return AccessResult::allowed()->cachePerPermissions();
}
// Permissions only apply to own entities.
$is_owner = ($account->id() && $account->id() === $entity->getOwnerId());
$is_owner_access = AccessResult::allowedIf($is_owner)
->addCacheableDependency($entity);
$operations = ['view', 'update', 'delete'];
if (!in_array($operation, $operations)) {
$reason = sprintf(
'Supported operations on the entity are %s',
implode(', ', $operations)
);
return AccessResult::neutral($reason);
}
return $is_owner_access->andIf(AccessResult::allowedIfHasPermission(
$account,
sprintf('%s own %s entities', $operation, static::$name)
)->cachePerPermissions());
}
/**
* {@inheritdoc}
*/
protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
$admin_access = parent::checkCreateAccess($account, $context, $entity_bundle);
return $admin_access->orIf(AccessResult::allowedIfHasPermission(
$account,
sprintf('add %s entities', static::$name),
));
}
}

View File

@@ -0,0 +1,75 @@
<?php
namespace Drupal\consumers;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityListBuilder;
/**
* Defines a class to build a listing of Access Token entities.
*/
class ConsumerListBuilder extends EntityListBuilder {
/**
* {@inheritdoc}
*/
public function buildHeader() {
$header['client_id'] = $this->t('Client ID');
$header['uuid'] = $this->t('UUID');
$header['label'] = $this->t('Label');
$header['is_default'] = $this->t('Is Default?');
$context = ['type' => 'header'];
$this->moduleHandler()->alter('consumers_list', $header, $context);
$header = $header + parent::buildHeader();
return $header;
}
/**
* {@inheritdoc}
*/
public function buildRow(EntityInterface $entity) {
/** @var \Drupal\consumers\Entity\ConsumerInterface $entity */
$row['client_id'] = $entity->getClientId();
$row['uuid'] = $entity->uuid();
$row['label'] = $entity->toLink();
$ops = [
'#type' => 'operations',
'#links' => [
[
'title' => $this->t('Make Default'),
'url' => $entity->toUrl('make-default-form', [
'query' => $this->getDestinationArray(),
]),
],
],
];
$row['is_default'] = $entity->get('is_default')->value
? ['data' => $this->t('Default')]
: ['data' => $ops];
$context = ['type' => 'row', 'entity' => $entity];
$this->moduleHandler()->alter('consumers_list', $row, $context);
$row = $row + parent::buildRow($entity);
return $row;
}
/**
* {@inheritdoc}
*/
public function getOperations(EntityInterface $entity) {
$operations = parent::getOperations($entity);
if (
$entity->access('update') &&
$entity->hasLinkTemplate('make-default-form') &&
!$entity->get('is_default')->value
) {
$operations['make-default'] = [
'title' => $this->t('Make Default'),
'weight' => 10,
'url' => $this->ensureDestination($entity->toUrl('make-default-form')),
];
}
return $operations;
}
}

View File

@@ -0,0 +1,69 @@
<?php
namespace Drupal\consumers;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Routing\EnhancerInterface;
use Drupal\jsonapi\Routing\Routes;
use Symfony\Component\HttpFoundation\Request;
/**
* Adds appropriate cache contexts if a consumer request is made.
*/
class ConsumerRouteEnhancer implements EnhancerInterface {
/**
* The cache context by which vary the loaded data.
*
* @var string
*/
const CACHE_CONTEXT = 'url.query_args:consumerId';
/**
* The consumer negotiator.
*
* @var \Drupal\consumers\Negotiator
*/
protected $consumerNegotiator;
/**
* The module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* ConsumerRouteEnhancer constructor.
*
* @param \Drupal\consumers\Negotiator $negotiator
* The consumer negotiator.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
*/
public function __construct(Negotiator $negotiator, ModuleHandlerInterface $module_handler) {
$this->consumerNegotiator = $negotiator;
$this->moduleHandler = $module_handler;
}
/**
* {@inheritdoc}
*/
public function enhance(array $defaults, Request $request) {
if (!$this->moduleHandler->moduleExists('jsonapi') ||
!Routes::isJsonApiRequest($defaults) ||
!Routes::getResourceTypeNameFromParameters($defaults)
) {
return $defaults;
}
if (isset($defaults['entity'])) {
assert($defaults['entity'] instanceof EntityInterface);
$defaults['entity']->addCacheContexts([static::CACHE_CONTEXT]);
}
return $defaults;
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace Drupal\consumers;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
/**
* Defines the storage handler class for consumers.
*
* This extends the base storage class, adding required special handling for
* consumers.
*/
class ConsumerStorage extends SqlContentEntityStorage {
/**
* {@inheritdoc}
*/
public function restore(EntityInterface $entity) {
/** @var \Drupal\consumers\Entity\ConsumerInterface $entity */
// Special handling for the secret field added by simple_oauth,
// make sure that it is not hashed again.
if ($entity->hasField('secret')) {
$entity->get('secret')->pre_hashed = TRUE;
}
parent::restore($entity);
}
}

View File

@@ -0,0 +1,274 @@
<?php
namespace Drupal\consumers\Entity;
use Drupal\Core\Access\AccessException;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Utility\Error;
use Drupal\user\EntityOwnerTrait;
/**
* Defines the Consumer entity.
*
* @ContentEntityType(
* id = "consumer",
* label = @Translation("Consumer"),
* label_collection = @Translation("Consumers"),
* label_singular = @Translation("consumer"),
* label_plural = @Translation("consumers"),
* handlers = {
* "list_builder" = "Drupal\consumers\ConsumerListBuilder",
* "form" = {
* "default" = "Drupal\consumers\Entity\Form\ConsumerForm",
* "add" = "Drupal\consumers\Entity\Form\ConsumerForm",
* "edit" = "Drupal\consumers\Entity\Form\ConsumerForm",
* "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
* "make-default" = "Drupal\consumers\Entity\Form\MakeDefaultForm",
* },
* "route_provider" = {
* "html" = "Drupal\consumers\Entity\Routing\HtmlRouteProvider",
* },
* "views_data" = "\Drupal\views\EntityViewsData",
* "access" = "Drupal\consumers\AccessControlHandler",
* "storage" = "Drupal\consumers\ConsumerStorage",
* },
* base_table = "consumer",
* data_table = "consumer_field_data",
* translatable = TRUE,
* admin_permission = "administer consumer entities",
* entity_keys = {
* "id" = "id",
* "label" = "label",
* "uuid" = "uuid",
* "langcode" = "langcode",
* "owner" = "owner_id",
* },
* links = {
* "canonical" = "/admin/config/services/consumer/{consumer}",
* "collection" = "/admin/config/services/consumer",
* "add-form" = "/admin/config/services/consumer/add",
* "edit-form" = "/admin/config/services/consumer/{consumer}/edit",
* "delete-form" = "/admin/config/services/consumer/{consumer}/delete",
* "make-default-form" = "/admin/config/services/consumer/{consumer}/make-default",
* }
* )
*/
class Consumer extends ContentEntityBase implements ConsumerInterface {
use EntityChangedTrait;
use EntityOwnerTrait;
/**
* {@inheritdoc}
*/
public function preSave(EntityStorageInterface $storage) {
parent::preSave($storage);
$was_not_default = is_null($this->original)
|| !$this->original->get('is_default')->value;
if ($this->get('is_default')->value && $was_not_default) {
// If we are making this the new default consumer.
try {
$this->removeDefaultConsumerFlags();
}
catch (AccessException $exception) {
// Backwards compatibility of error logging. See
// https://www.drupal.org/node/2932520. This can be removed when we no
// longer support Drupal > 10.1.
if (version_compare(\Drupal::VERSION, '10.1', '>=')) {
$logger = \Drupal::logger('consumers');
Error::logException($logger, $exception);
}
else {
// @phpstan-ignore-next-line
watchdog_exception('consumers', $exception);
}
\Drupal::messenger()->addError($exception->getMessage());
$this->set('is_default', FALSE);
}
}
foreach (array_keys($this->getTranslationLanguages()) as $langcode) {
$translation = $this->getTranslation($langcode);
// If no owner has been set explicitly, make the anonymous user the owner.
if (!$translation->get('owner_id')->entity) {
$translation->set('owner_id', 0);
}
}
}
/**
* {@inheritdoc}
*/
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
$fields = parent::baseFieldDefinitions($entity_type);
$fields += static::ownerBaseFieldDefinitions($entity_type);
// Prepare args for translatable markup.
$args['@label'] = $entity_type->getSingularLabel();
$fields['client_id'] = BaseFieldDefinition::create('string')
->setLabel(new TranslatableMarkup('Client ID'))
->setDescription(new TranslatableMarkup('The client ID associated with this @label. This is an arbitrary unique field, like a machine name.', $args))
->setRequired(TRUE)
->setRevisionable(TRUE)
->addConstraint('UniqueField')
->setSetting('max_length', 255)
->setDisplayOptions('form', [
'type' => 'string_textfield',
'weight' => -4,
])
->setDisplayConfigurable('form', TRUE);
$fields['label'] = BaseFieldDefinition::create('string')
->setLabel(new TranslatableMarkup('Label'))
->setDescription(new TranslatableMarkup('The @label label.', $args))
->setRequired(TRUE)
->setTranslatable(TRUE)
->setRevisionable(TRUE)
->setSetting('max_length', 255)
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'string',
'weight' => -5,
])
->setDisplayOptions('form', [
'type' => 'string_textfield',
'weight' => -5,
])
->setDisplayConfigurable('form', TRUE);
$fields['description'] = BaseFieldDefinition::create('string_long')
->setLabel(t('Description'))
->setDescription(t('A description of the @label. This text will be shown to the users to authorize sharing their data to create an access token.', $args))
->setTranslatable(TRUE)
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'string',
'weight' => 0,
])
->setDisplayConfigurable('view', TRUE)
->setDisplayOptions('form', [
'type' => 'string_textfield',
'weight' => 0,
])
->setDisplayConfigurable('form', TRUE);
$fields['image'] = BaseFieldDefinition::create('image')
->setLabel(t('Logo'))
->setDescription(t('Logo of the @label.', $args))
->setRevisionable(TRUE)
->setTranslatable(TRUE)
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'image',
'weight' => -3,
])
->setDisplayOptions('form', [
'type' => 'image_image',
'weight' => -3,
'settings' => [
'preview_image_style' => 'thumbnail',
'progress_indicator' => 'throbber',
],
])
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);
$fields['third_party'] = BaseFieldDefinition::create('boolean')
->setLabel(new TranslatableMarkup('Is this @label 3rd party?', $args))
->setDescription(new TranslatableMarkup('Mark this if the organization behind this @label is not the same as the one behind the Drupal API.', $args))
->setDisplayOptions('view', [
'label' => 'inline',
'type' => 'boolean',
'weight' => 4,
])
->setDisplayOptions('form', [
'weight' => 4,
])
->setRevisionable(TRUE)
->setTranslatable(TRUE)
->setDefaultValue(TRUE);
$fields['is_default'] = BaseFieldDefinition::create('boolean')
->setLabel(new TranslatableMarkup('Is this the default @label?', $args))
->setDescription(new TranslatableMarkup('There can only be one default @label. Mark this to use this @label when none other applies.', $args))
->setDisplayOptions('view', [
'label' => 'inline',
'type' => 'boolean',
'weight' => 4,
])
->setDisplayOptions('form', [
'weight' => 4,
])
->setRevisionable(TRUE)
->setTranslatable(TRUE)
->setDefaultValue(FALSE);
return $fields;
}
/**
* Removes the is_default flag from other consumers.
*
* @throws \Drupal\Component\Plugin\Exception\PluginException
* @throws \Drupal\Core\Access\AccessException
*/
protected function removeDefaultConsumerFlags() {
// Find the old defaults.
$entity_storage = $this->entityTypeManager()
->getStorage($this->getEntityTypeId());
$entity_ids = $entity_storage
->getQuery()
->accessCheck(TRUE)
->condition('is_default', TRUE)
->condition('id', $this->id(), '!=')
->execute();
$entity_ids = $entity_ids ? array_values($entity_ids) : [];
if (empty($entity_ids)) {
$default_entities = [];
}
else {
$default_entities = $entity_storage->loadMultiple($entity_ids);
$default_entities = array_map(
static::setDefaultTo(FALSE),
$default_entities
);
$invalid_entities = array_filter($default_entities, function (ConsumerInterface $consumer) {
return !$consumer->access('update', NULL, TRUE)->isAllowed();
});
if (count($invalid_entities)) {
throw new AccessException('Unable to change the current default consumer. Permission denied.');
}
}
array_map([$entity_storage, 'save'], $default_entities);
}
/**
* Gets closure that will set is_default to the selected value for an entity.
*
* @param bool $value
* The final value of the "is_default" field.
*
* @return \Closure
* The closure that will set the "is_default" field to the selected value.
*/
protected static function setDefaultTo($value) {
return function (ConsumerInterface $consumer) use ($value) {
$consumer->set('is_default', $value);
return $consumer;
};
}
/**
* {@inheritdoc}
*/
public function getClientId(): string {
return $this->get('client_id')->value;
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace Drupal\consumers\Entity;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\user\EntityOwnerInterface;
/**
* Provides an interface defining a consumer entity.
*/
interface ConsumerInterface extends ContentEntityInterface, EntityOwnerInterface {
/**
* Gets the client ID.
*
* @return string
* The client ID.
*/
public function getClientId(): string;
}

View File

@@ -0,0 +1,70 @@
<?php
namespace Drupal\consumers\Entity\Form;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;
/**
* Form controller for Consumer edit forms.
*/
class ConsumerForm extends ContentEntityForm {
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$form['is_default']['#access'] = FALSE;
$form['client_id']['generate'] = [
'#type' => 'submit',
'#value' => $this->t('Generate random Client ID'),
'#limit_validation_errors' => [$form['client_id']['widget']['#parents']],
'#attributes' => [
'class' => [
'button--small',
],
],
'#ajax' => [
'callback' => [$this, 'generateClientId'],
'disable-refocus' => TRUE,
'wrapper' => 'edit-client-id-wrapper',
],
];
return $form;
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
$status = $this->entity->save();
$label = $this->entity->label();
$args = [
'%label' => $label,
'@type' => $this->entity->getEntityType()->getLabel(),
];
switch ($status) {
case SAVED_NEW:
$this->messenger()->addMessage($this->t('Created the %label @type.', $args));
break;
default:
$this->messenger()->addMessage($this->t('Saved the %label @type.', $args));
}
$form_state->setRedirect('entity.consumer.collection');
return $status;
}
/**
* AJAX callback that generates the client ID.
*/
public function generateClientId(array &$form, FormStateInterface $form_state): array {
$form['client_id']['widget'][0]['value']['#value'] = Crypt::randomBytesBase64();
return $form['client_id'];
}
}

View File

@@ -0,0 +1,64 @@
<?php
namespace Drupal\consumers\Entity\Form;
use Drupal\Core\Entity\ContentEntityConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* Form controller for the Consumer make default form.
*
* @ingroup consumers
*/
class MakeDefaultForm extends ContentEntityConfirmFormBase {
/**
* {@inheritdoc}
*/
public function getQuestion() {
return $this->t('Are you sure you want to make %consumer the default @label?', [
'%consumer' => $this->entity->label(),
'@label' => $this->entity->getEntityType()->getSingularLabel(),
]);
}
/**
* {@inheritdoc}
*/
public function getDescription() {
return $this->t('The @label currently marked as default will lose this property, since there can only be one default @label. This may break current assumptions in existing client-side applications.', [
'@label' => $this->entity->getEntityType()->getSingularLabel(),
]);
}
/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return Url::fromRoute('entity.consumer.collection');
}
/**
* {@inheritdoc}
*/
public function getConfirmText() {
return $this->t('Make Default');
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Make the submitted entity the new default.
/** @var \Drupal\consumers\Entity\ConsumerInterface $entity */
$entity = $this->getEntity();
if ($entity->get('is_default')->value) {
// This is already the default. Do nothing.
return;
}
$entity->set('is_default', TRUE);
$entity->save();
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace Drupal\consumers\Entity\Routing;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider;
use Symfony\Component\Routing\Route;
/**
* Provides HTML routes for the Consumer entity.
*/
class HtmlRouteProvider extends DefaultHtmlRouteProvider {
/**
* {@inheritdoc}
*/
public function getRoutes(EntityTypeInterface $entity_type) {
$collection = parent::getRoutes($entity_type);
$route = new Route($entity_type->getLinkTemplate('make-default-form'));
$route
->addDefaults([
'_entity_form' => 'consumer.make-default',
'_title_callback' => '\Drupal\Core\Entity\Controller\EntityController::title',
])
->setRequirement('_entity_access', 'consumer.update')
->setOption('parameters', ['consumer' => ['type' => 'entity:consumer']]);
$collection->add(
'entity.consumer.make_default_form',
$route
);
return $collection;
}
}

View File

@@ -0,0 +1,75 @@
<?php
namespace Drupal\consumers\EventSubscriber;
use Drupal\consumers\MissingConsumer;
use Drupal\consumers\Negotiator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Vary header by consumer.
*/
class ConsumerVaryEventSubscriber implements EventSubscriberInterface {
/**
* The consumer id header key.
*
* @var string
*/
const CONSUMER_ID_HEADER = 'X-Consumer-ID';
/**
* The consumer negotiator.
*
* @var \Drupal\consumers\Negotiator
*/
protected $negotiator;
/**
* ConsumerVaryEventSubscriber constructor.
*
* @param \Drupal\consumers\Negotiator $negotiator
* The consumer negotiator.
*/
public function __construct(Negotiator $negotiator) {
$this->negotiator = $negotiator;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
return [
KernelEvents::RESPONSE => 'onRespond',
];
}
/**
* React on response and set the Vary header.
*/
public function onRespond(ResponseEvent $event) {
$response = $event->getResponse();
try {
$consumer = $this->negotiator->negotiateFromRequest($event->getRequest());
}
catch (MissingConsumer $e) {
// If there's no consumer in the header, and no default consumer then we
// don't need to add any Vary headers.
$consumer = FALSE;
}
if ($consumer) {
// Add consumer id to headers.
$response->headers->set(self::CONSUMER_ID_HEADER, $consumer->getClientId());
// Add consumer id to vary headers.
$vary_headers = $response->getVary();
$vary_headers[] = self::CONSUMER_ID_HEADER;
$response->setVary($vary_headers);
}
}
}

View File

@@ -0,0 +1,8 @@
<?php
namespace Drupal\consumers;
/**
* Exception thrown when a consumer is missing.
*/
class MissingConsumer extends \Exception {}

View File

@@ -0,0 +1,160 @@
<?php
namespace Drupal\consumers;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Utility\Error;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Extracts the consumer information from the given context.
*
* @internal
*/
class Negotiator {
use LoggerAwareTrait;
/**
* Protected requestStack.
*
* @var \Symfony\Component\HttpFoundation\RequestStack
*/
protected $requestStack;
/**
* The entity storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $storage;
/**
* The default consumer.
*
* @var \Drupal\consumers\Entity\ConsumerInterface
*/
protected $defaultConsumer;
/**
* Instantiates a new Negotiator object.
*/
public function __construct(RequestStack $request_stack, LoggerInterface $logger) {
$this->requestStack = $request_stack;
$this->logger = $logger;
}
/**
* Obtains the consumer from the request.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The request.
*
* @return \Drupal\consumers\Entity\ConsumerInterface|null
* The consumer.
*
* @throws \Drupal\consumers\MissingConsumer
*/
protected function doNegotiateFromRequest(Request $request) {
// There are several ways to negotiate the consumer:
// 1. Via a custom header.
$consumer_id = $request->headers->get('X-Consumer-ID');
if (!$consumer_id) {
// 2. Via a query string parameter.
$consumer_id = $request->query->get('consumerId');
if (!$consumer_id && $request->query->has('_consumer_id')) {
$this->logger->warning('The "_consumer_id" query string parameter is deprecated and it will be removed in the next major version of the module, please use "consumerId" instead.');
$consumer_id = $request->query->get('_consumer_id');
}
}
if ($consumer_id) {
try {
$results = $this->storage->loadByProperties(['client_id' => $consumer_id]);
/** @var \Drupal\consumers\Entity\ConsumerInterface $consumer */
$consumer = !empty($results) ? reset($results) : $results;
}
catch (EntityStorageException $exception) {
// Backwards compatibility of error logging. See
// https://www.drupal.org/node/2932520. This can be removed when we no
// longer support Drupal > 10.1.
if (version_compare(\Drupal::VERSION, '10.1', '>=')) {
$logger = \Drupal::logger('consumers');
Error::logException($logger, $exception);
}
else {
// @phpstan-ignore-next-line
watchdog_exception('consumers', $exception);
}
}
}
if (empty($consumer)) {
$consumer = $this->loadDefaultConsumer();
}
return $consumer;
}
/**
* Obtains the consumer from the request.
*
* @param \Symfony\Component\HttpFoundation\Request|null $request
* The request object to inspect for a consumer. Set to NULL to use the
* current request.
*
* @return \Drupal\consumers\Entity\ConsumerInterface|null
* The consumer.
*
* @throws \Drupal\consumers\MissingConsumer
*/
public function negotiateFromRequest(Request $request = NULL) {
// If the request is not provided, use the request from the stack.
$request = $request ? $request : $this->requestStack->getCurrentRequest();
$consumer = $this->doNegotiateFromRequest($request);
$request->attributes->set('consumer_id', $consumer->getClientId());
return $consumer;
}
/**
* Finds and loads the default consumer.
*
* @return \Drupal\consumers\Entity\ConsumerInterface
* The consumer entity.
*
* @throws \Drupal\consumers\MissingConsumer
*/
protected function loadDefaultConsumer() {
if (!empty($this->defaultConsumer)) {
return $this->defaultConsumer;
}
// Find the default consumer.
$results = $this->storage->getQuery()
->accessCheck(TRUE)
->condition('is_default', TRUE)
->execute();
$consumer_id = reset($results);
if (!$consumer_id) {
// Throw if there is no default consumer.
throw new MissingConsumer('Unable to find the default consumer.');
}
$this->defaultConsumer = $this->storage->load($consumer_id);
return $this->defaultConsumer;
}
/**
* Sets the storage from the entity type manager.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*
* @throws \Drupal\Component\Plugin\Exception\PluginException
*/
public function setEntityStorage(EntityTypeManagerInterface $entity_type_manager) {
$this->storage = $entity_type_manager->getStorage('consumer');
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace Drupal\consumers\Plugin\Menu;
use Drupal\Core\Menu\MenuLinkDefault;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* A menu link to Consumers collection page.
*/
class ConsumersCollectionLink extends MenuLinkDefault {
use StringTranslationTrait;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
$instance->entityTypeManager = $container->get('entity_type.manager');
$instance->setStringTranslation($container->get('string_translation'));
return $instance;
}
/**
* {@inheritdoc}
*/
public function getTitle() {
return $this->entityTypeManager->getDefinition('consumer')->getCollectionLabel();
}
/**
* {@inheritdoc}
*/
public function getDescription() {
return $this->t('Register and configure the decoupled @label to your API.', [
'@label' => $this->entityTypeManager->getDefinition('consumer')->getPluralLabel(),
]);
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace Drupal\consumers\Plugin\Menu\LocalAction;
use Drupal\Core\Menu\LocalActionDefault;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Provides a local action for adding a consumer.
*/
class AddConsumerAction extends LocalActionDefault {
use StringTranslationTrait;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
$instance->entityTypeManager = $container->get('entity_type.manager');
$instance->setStringTranslation($container->get('string_translation'));
return $instance;
}
/**
* {@inheritdoc}
*/
public function getTitle(Request $request = NULL) {
return $this->t('Add @label', [
'@label' => $this->entityTypeManager->getDefinition('consumer')->getLabel(),
]);
}
}