toolbar_plus-1.0.x-dev/src/Controller/LoadEditablePage.php
src/Controller/LoadEditablePage.php
<?php
declare(strict_types=1);
namespace Drupal\toolbar_plus\Controller;
use Drupal\toolbar_plus\ToolbarPlusUi;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\edit_plus\ParamConverter\EntityConverter;
use Drupal\Core\TypedData\TypedDataManagerInterface;
use Drupal\toolbar_plus\LoadEditablePageResponseTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Returns responses for Toolbar + routes.
*/
final class LoadEditablePage extends ControllerBase {
use LoadEditablePageResponseTrait;
public function __construct(
protected readonly EntityConverter $entityConverter,
protected readonly TypedDataManagerInterface $typedDataManager,
protected readonly ToolbarPlusUi $toolbarPlusUi,
) {}
public static function create(ContainerInterface $container) {
return new static(
$container->get('edit_plus.param_converter.entity'),
$container->get('typed_data_manager'),
$container->get('toolbar_plus.ui'),
);
}
/**
* Load editable page.
*
* When the user initially views a node there are no UI attributes in the
* markup. When the user enables Edit Mode an AJAX call to this controller
* is made to reload the page with UI attributes in the markup. Tool plugins
* should check $this->toolbarPlusUi->getEditModeState() before adding markup
* to the page.
*/
public function __invoke(EntityInterface $entity, string $view_mode) {
$state = $this->toolbarPlusUi->getEditModeState();
$content = $this->getEmptyContent($entity, $view_mode);
if (!$this->toolbarPlusUi->isValidViewMode($entity, $view_mode)) {
$content['#markup'] = $this->t('Edit +: Invalid view mode for @label', ['@label' => $entity->label()]);
}
if (empty($content['#markup']) && !$entity->access('update')) {
$content['#markup'] = $this->t("You don't have permission to edit this.");
}
// Lock editing the entity down to one workspace at a time.
// @see toolbar_plus_entity_view_alter for the non-AJAX version.
if (empty($content['#markup']) && \Drupal::moduleHandler()->moduleExists('workspaces') && $state === 'enabled') {
$constraints = array_values(array_filter($entity->getTypedData()->getConstraints(), function ($constraint) {
return $constraint instanceof \Drupal\workspaces\Plugin\Validation\Constraint\EntityWorkspaceConflictConstraint;
}));
if (!empty($constraints)) {
$violations = $this->typedDataManager->getValidator()->validate(
$entity->getTypedData(),
$constraints[0]
);
if (count($violations)) {
$content['#markup'] = $violations->get(0)->getMessage();
}
}
}
if (empty($content['#markup']) && \Drupal::moduleHandler()->moduleExists('edit_plus') && $state === 'enabled') {
$entity = $this->entityConverter->loadEntityFromTempstore($entity);
}
if (empty($content['#markup'])) {
$content = $this->entityTypeManager()->getViewBuilder($entity->getEntityTypeId())->view($entity, $view_mode);
}
return $this->getAjaxReplaceResponse($entity, $view_mode, $content);
}
}
