NodeCloneFormController.php in Node clone 8
File
src/Controller/NodeCloneFormController.php
View source
<?php
namespace Drupal\node_clone\Controller;
use Drupal\Core\Access\AccessResultAllowed;
use Drupal\Core\Access\AccessResultForbidden;
use Drupal\Core\Controller\ControllerResolverInterface;
use Drupal\Core\Controller\FormController;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\node\Access\NodeAddAccessCheck;
use Drupal\node\Entity\NodeType;
use Drupal\node\NodeInterface;
class NodeCloneFormController extends FormController {
use StringTranslationTrait;
protected $entityManager;
protected $nodeAddAccessCheck;
public function __construct(ControllerResolverInterface $resolver, FormBuilderInterface $form_builder, EntityManagerInterface $manager, NodeAddAccessCheck $node_add_access) {
parent::__construct($resolver, $form_builder);
$this->entityManager = $manager;
$this->nodeAddAccessCheck = $node_add_access;
}
protected function getFormArgument(RouteMatchInterface $route_match) {
return 'node';
}
protected function getFormObject(RouteMatchInterface $route_match, $form_arg) {
$form_arg .= '.default';
list($entity_type_id, $operation) = explode('.', $form_arg);
$form_object = $this->entityManager
->getFormObject($entity_type_id, $operation);
$entity = $form_object
->getEntityFromRouteMatch($route_match, $entity_type_id);
$new_entity = $entity
->createDuplicate();
$new_entity
->setTitle($this
->t('Clone of ') . $new_entity
->getTitle());
$form_object
->setEntity($new_entity);
return $form_object;
}
public function access(AccountInterface $account, NodeInterface $node) {
if ($account
->hasPermission('clone node') || $node->uid->value === $account
->id() && $account
->hasPermission('clone own nodes')) {
$access = new AccessResultAllowed();
}
else {
$access = new AccessResultForbidden();
}
$access
->addCacheableDependency($node);
$access
->cachePerPermissions();
if ($access
->isAllowed()) {
$access = $access
->andIf($node
->access('view', $account, TRUE));
}
if ($access
->isAllowed()) {
$node_type = NodeType::load($node
->getType());
$access = $access
->andIf($this->nodeAddAccessCheck
->access($account, $node_type));
}
return $access;
}
}