/** * {@inheritdoc} */ public function access(Route $route, AccountInterface $account, RdfInterface $rdf_entity, $operation = 'view') { $graph = $route->getOption('graph_name'); $entity_type_id = $route->getOption('entity_type_id'); $storage = $this->entityManager->getStorage($entity_type_id); if (!$storage instanceof RdfEntitySparqlStorage) { throw new \Exception('Storage not supported.'); } // The active graph is the published graph. It is handled by the default // operation handler. // @todo: getActiveGraph is not the default. We should load from settings. $default_graph = $storage->getBundleGraphUri($rdf_entity->bundle(), 'default'); $requested_graph = $storage->getBundleGraphUri($rdf_entity->bundle(), $graph); if ($requested_graph == $default_graph) { return AccessResult::neutral(); } $active_graph_type = $storage->getRequestGraphs($rdf_entity->id()); // Check if there is an entity saved in the passed graph. $storage->setRequestGraphs($rdf_entity->id(), [$graph]); $entity = $storage->load($rdf_entity->id()); // Restore active graph. $storage->setRequestGraphs($rdf_entity->id(), $active_graph_type); // @todo: When the requested graph is the only one and it is not the // default, it is loaded in the default view, so maybe there is no need // to also show a separate tab. return AccessResult::allowedIf($entity && $this->checkAccess($rdf_entity, $route, $account, $operation, $graph))->cachePerPermissions()->addCacheableDependency($rdf_entity); }
/** * Constructs a new TaxTypeImporter. * * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager * The entity type manager. * @param string * The tax types folder of definitions. */ public function __construct(EntityTypeManagerInterface $entityTypeManager, TranslationInterface $stringTranslation, $taxTypesFolder = NULL) { $this->taxTypeStorage = $entityTypeManager->getStorage('commerce_tax_type'); $this->taxRateStorage = $entityTypeManager->getStorage('commerce_tax_rate'); $this->taxRateAmountStorage = $entityTypeManager->getStorage('commerce_tax_rate_amount'); $this->stringTranslation = $stringTranslation; $this->taxTypeRepository = new TaxTypeRepository($taxTypesFolder); }
protected function execute(InputInterface $input, OutputInterface $output) { $io = new DrupalStyle($input, $output); $moduleHandler = $this->moduleHandler; $moduleHandler->loadInclude('locale', 'inc', 'locale.translation'); $moduleHandler->loadInclude('locale', 'module'); $language = $input->getArgument('language'); $languagesObjects = locale_translatable_language_list(); $languages = $this->site->getStandardLanguages(); if (isset($languagesObjects[$language])) { $languageEntity = $languagesObjects[$language]; } elseif (array_search($language, $languages)) { $langcode = array_search($language, $languages); $languageEntity = $languagesObjects[$langcode]; } else { $io->error(sprintf($this->trans('commands.locale.language.delete.messages.invalid-language'), $language)); return 1; } try { $configurable_language_storage = $this->entityTypeManager->getStorage('configurable_language'); $configurable_language_storage->load($languageEntity->getId())->delete(); $io->info(sprintf($this->trans('commands.locale.language.delete.messages.language-deleted-successfully'), $languageEntity->getName())); } catch (\Exception $e) { $io->error($e->getMessage()); return 1; } return 0; }
/** * Sets up the entity type manager to be tested. * * @param \Drupal\Core\Entity\EntityTypeInterface[]|\Prophecy\Prophecy\ProphecyInterface[] $definitions * (optional) An array of entity type definitions. */ protected function setUpEntityTypeDefinitions($definitions = []) { $class = $this->getMockClass(EntityInterface::class); foreach ($definitions as $key => $entity_type) { // \Drupal\Core\Entity\EntityTypeInterface::getLinkTemplates() is called // by \Drupal\Core\Entity\EntityManager::processDefinition() so it must // always be mocked. $entity_type->getLinkTemplates()->willReturn([]); // Give the entity type a legitimate class to return. $entity_type->getClass()->willReturn($class); $definitions[$key] = $entity_type->reveal(); } $this->entityTypeManager->getDefinition(Argument::cetera())->will(function ($args) use($definitions) { $entity_type_id = $args[0]; $exception_on_invalid = $args[1]; if (isset($definitions[$entity_type_id])) { return $definitions[$entity_type_id]; } elseif (!$exception_on_invalid) { return NULL; } else { throw new PluginNotFoundException($entity_type_id); } }); $this->entityTypeManager->getDefinitions()->willReturn($definitions); }
/** * Constructs a new AddToCartForm object. * * @param \Drupal\commerce_cart\CartManagerInterface $cart_manager * The cart manager. * @param \Drupal\commerce_cart\CartProviderInterface $cart_provider * The cart provider. * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager 49 The entity type manager. * @param \Drupal\commerce_store\StoreContextInterface $store_context * The store context. */ public function __construct(CartManagerInterface $cart_manager, CartProviderInterface $cart_provider, EntityTypeManagerInterface $entity_type_manager, StoreContextInterface $store_context) { $this->cartManager = $cart_manager; $this->cartProvider = $cart_provider; $this->variationStorage = $entity_type_manager->getStorage('commerce_product_variation'); $this->storeContext = $store_context; }
/** * Reacts on the given event and invokes configured reaction rules. * * @param \Symfony\Component\EventDispatcher\Event $event * The event object containing context for the event. * @param string $event_name * The event name. */ public function onRulesEvent(Event $event, $event_name) { // Load reaction rule config entities by $event_name. $storage = $this->entityTypeManager->getStorage('rules_reaction_rule'); // @todo Only load active reaction rules here. $configs = $storage->loadByProperties(['event' => $event_name]); // Set up an execution state with the event context. $event_definition = $this->eventManager->getDefinition($event_name); $state = ExecutionState::create(); foreach ($event_definition['context'] as $context_name => $context_definition) { // If this is a GenericEvent get the context for the rule from the event // arguments. if ($event instanceof GenericEvent) { $value = $event->getArgument($context_name); } else { $value = $event->{$context_name}; } $state->setVariable($context_name, $context_definition, $value); } // Loop over all rules and execute them. foreach ($configs as $config) { /** @var \Drupal\rules\Entity\ReactionRuleConfig $config */ $config->getExpression()->executeWithState($state); } $state->autoSave(); }
/** * Constructs a new instance. * * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory * @param \Drupal\currency\EventDispatcherInterface $event_dispatcher */ public function __construct(EntityTypeManagerInterface $entity_type_manager, LanguageManagerInterface $language_manager, ConfigFactoryInterface $config_factory, EventDispatcherInterface $event_dispatcher) { $this->configFactory = $config_factory; $this->currencyLocaleStorage = $entity_type_manager->getStorage('currency_locale'); $this->eventDispatcher = $event_dispatcher; $this->languageManager = $language_manager; }
/** * Checks access to create an entity of any bundle for the given route. * * @param \Symfony\Component\Routing\Route $route * The route to check against. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match * The parameterized route. * @param \Drupal\Core\Session\AccountInterface $account * The currently logged in account. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */ public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account) { $entity_type_id = $route->getRequirement($this->requirementsKey); $entity_type = $this->entityTypeManager->getDefinition($entity_type_id); $access_control_handler = $this->entityTypeManager->getAccessControlHandler($entity_type_id); // In case there is no "bundle" entity key, check create access with no // bundle specified. if (!$entity_type->hasKey('bundle')) { return $access_control_handler->createAccess(NULL, $account, [], TRUE); } $access = AccessResult::neutral(); $bundles = array_keys($this->entityTypeBundleInfo->getBundleInfo($entity_type_id)); // Include list cache tag as access might change if more bundles are added. if ($entity_type->getBundleEntityType()) { $access->addCacheTags($this->entityTypeManager->getDefinition($entity_type->getBundleEntityType())->getListCacheTags()); // Check if the user is allowed to create new bundles. If so, allow // access, so the add page can show a link to create one. // @see \Drupal\Core\Entity\Controller\EntityController::addPage() $bundle_access_control_handler = $this->entityTypeManager->getAccessControlHandler($entity_type->getBundleEntityType()); $access = $access->orIf($bundle_access_control_handler->createAccess(NULL, $account, [], TRUE)); if ($access->isAllowed()) { return $access; } } // Check whether an entity of any bundle may be created. foreach ($bundles as $bundle) { $access = $access->orIf($access_control_handler->createAccess($bundle, $account, [], TRUE)); // In case there is a least one bundle user can create entities for, // access is allowed. if ($access->isAllowed()) { break; } } return $access; }
/** * {@inheritdoc} */ protected function alterRoutes(RouteCollection $collection) { foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) { if ($route = $this->getEntityCloneRoute($entity_type)) { $collection->add("entity.$entity_type_id.clone_form", $route); } } }
protected function checkAccess(ContentEntityInterface $entity, AccountInterface $account, $operation = 'view') { $entity_type = $entity->getEntityType(); $entity_type_id = $entity->getEntityTypeId(); $entity_access = $this->entityTypeManager->getAccessControlHandler($entity_type_id); /** @var \Drupal\Core\Entity\EntityStorageInterface $entity_storage */ $entity_storage = $this->entityTypeManager->getStorage($entity_type_id); $map = ['view' => "view all {$entity_type_id} revisions", 'list' => "view all {$entity_type_id} revisions", 'update' => "revert all {$entity_type_id} revisions", 'delete' => "delete all {$entity_type_id} revisions"]; $bundle = $entity->bundle(); $type_map = ['view' => "view {$entity_type_id} {$bundle} revisions", 'list' => "view {$entity_type_id} {$bundle} revisions", 'update' => "revert {$entity_type_id} {$bundle} revisions", 'delete' => "delete {$entity_type_id} {$bundle} revisions"]; if (!$entity || !isset($map[$operation]) || !isset($type_map[$operation])) { // If there was no node to check against, or the $op was not one of the // supported ones, we return access denied. return FALSE; } // Statically cache access by revision ID, language code, user account ID, // and operation. $langcode = $entity->language()->getId(); $cid = $entity->getRevisionId() . ':' . $langcode . ':' . $account->id() . ':' . $operation; if (!isset($this->accessCache[$cid])) { // Perform basic permission checks first. if (!$account->hasPermission($map[$operation]) && !$account->hasPermission($type_map[$operation]) && !$account->hasPermission('administer nodes')) { $this->accessCache[$cid] = FALSE; return FALSE; } if (($admin_permission = $entity_type->getAdminPermission()) && $account->hasPermission($admin_permission)) { $this->accessCache[$cid] = TRUE; } else { // First check the access to the default revision and finally, if the // node passed in is not the default revision then access to that, too. $this->accessCache[$cid] = $entity_access->access($entity_storage->load($entity->id()), $operation, $account) && ($entity->isDefaultRevision() || $entity_access->access($entity, $operation, $account)); } } return $this->accessCache[$cid]; }
/** * Destroy all existing terms before import * @param $vid * @param $io */ private function deleteExistingTerms($vid = null, DrupalStyle $io) { //Load the vid $termStorage = $this->entityTypeManager->getStorage('taxonomy_term'); $vocabularies = $this->entityTypeManager->getStorage('taxonomy_vocabulary')->loadMultiple(); if ($vid !== 'all') { $vid = [$vid]; } else { $vid = array_keys($vocabularies); } foreach ($vid as $item) { if (!isset($vocabularies[$item])) { $io->error("Invalid vid: {$item}."); } $vocabulary = $vocabularies[$item]; $terms = $termStorage->loadTree($vocabulary->id()); foreach ($terms as $term) { $treal = $termStorage->load($term->tid); if ($treal !== null) { $io->info("Deleting '{$term->name}' and all translations."); $treal->delete(); } } } }
/** * {@inheritdoc} */ public function getDescription() { $locked = $this->tempStore->getMetadata($this->entity->id()); $account = $this->entityTypeManager->getStorage('user')->load($locked->owner); $username = array('#theme' => 'username', '#account' => $account); return $this->t('By breaking this lock, any unsaved changes made by @user will be lost.', array('@user' => $this->renderer->render($username))); }
/** * {@inheritdoc} */ public function getDescription() { $locked = $this->rulesUiHandler->getLockMetaData(); $account = $this->entityTypeManager->getStorage('user')->load($locked->owner); $username = ['#theme' => 'username', '#account' => $account]; return $this->t('By breaking this lock, any unsaved changes made by @user will be lost.', ['@user' => $this->renderer->render($username)]); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $io = new DrupalStyle($input, $output); $styles = $input->getArgument('styles'); $result = 0; $imageStyle = $this->entityTypeManager->getStorage('image_style'); $stylesNames = []; if (in_array('all', $styles)) { $styles = $imageStyle->loadMultiple(); foreach ($styles as $style) { $stylesNames[] = $style->get('name'); } $styles = $stylesNames; } foreach ($styles as $style) { try { $io->info(sprintf($this->trans('commands.image.styles.flush.messages.executing-flush'), $style)); $imageStyle->load($style)->flush(); } catch (\Exception $e) { watchdog_exception('image', $e); $io->error($e->getMessage()); $result = 1; } } $io->success($this->trans('commands.image.styles.flush.messages.success')); return $result; }
/** * Constructs the target plugin. */ public function __construct(array $configuration, $plugin_id, array $plugin_definition, EntityTypeManagerInterface $entity_type_manager, AccountInterface $current_user) { parent::__construct($configuration, $plugin_id, $plugin_definition, $current_user); $this->paragraphStorage = $entity_type_manager->getStorage('paragraph'); $this->paragraphsTypeStorage = $entity_type_manager->getStorage('paragraphs_type'); $this->fieldConfigStorage = $entity_type_manager->getStorage('field_config'); }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->entityTypeManager = $this->prophesize(EntityTypeManagerInterface::class); $this->languageManager = $this->prophesize(LanguageManagerInterface::class); $this->entityRepository = new EntityRepository($this->entityTypeManager->reveal(), $this->languageManager->reveal()); }
/** * Tests the clearCachedDefinitions() method. * * @covers ::clearCachedDefinitions */ public function testClearCachedDefinitions() { $this->entityTypeManager->clearCachedDefinitions()->shouldBeCalled(); $this->entityTypeRepository->clearCachedDefinitions()->shouldBeCalled(); $this->entityTypeBundleInfo->clearCachedBundles()->shouldBeCalled(); $this->entityFieldManager->clearCachedFieldDefinitions()->shouldBeCalled(); $this->entityManager->clearCachedDefinitions(); }
/** * {@inheritdoc} * * @covers ::__construct */ protected function setUp() { $this->pageStorage = $this->prophesize(ConfigEntityStorageInterface::class); $this->entityTypeManager = $this->prophesize(EntityTypeManagerInterface::class); $this->entityTypeManager->getStorage('page')->willReturn($this->pageStorage); $this->cacheTagsInvalidator = $this->prophesize(CacheTagsInvalidatorInterface::class); $this->routeSubscriber = new PageManagerRoutes($this->entityTypeManager->reveal(), $this->cacheTagsInvalidator->reveal()); }
/** * {@inheritdoc} */ public function build($entity_type_id, $entity_id, $flag_id) { $entity = $this->entityTypeManager->getStorage($entity_type_id)->load($entity_id); $flag = $this->flagService->getFlagById($flag_id); $link_type_plugin = $flag->getLinkTypePlugin(); $link = $link_type_plugin->getLink($flag, $entity); return $link; }
/** * {@inheritdoc} */ protected function setUp() { $this->pageVariantStorage = $this->prophesize(ConfigEntityStorageInterface::class); $this->entityTypeManager = $this->prophesize(EntityTypeManagerInterface::class); $this->entityTypeManager->getStorage('page_variant')->willReturn($this->pageVariantStorage); $this->currentPath = $this->prophesize(CurrentPathStack::class); $this->routeFilter = new VariantRouteFilter($this->entityTypeManager->reveal(), $this->currentPath->reveal()); }
/** * Get taxonomy permissions. * * @return array * Permissions array. */ public function permissions() { $permissions = []; foreach ($this->entityTypeManager->getStorage('taxonomy_vocabulary')->loadMultiple() as $vocabulary) { $permissions += ['view published terms in ' . $vocabulary->id() => ['title' => $this->t('View published terms in %vocabulary', ['%vocabulary' => $vocabulary->label()])], 'view unpublished terms in ' . $vocabulary->id() => ['title' => $this->t('View unpublished terms in %vocabulary', ['%vocabulary' => $vocabulary->label()])]]; } return $permissions; }
/** * {@inheritdoc} */ public function buildRow(EntityInterface $entity) { /** @var ScheduledUpdateTypeInterface $entity */ $row['label'] = $entity->label(); $row['target_type'] = $this->entityTypeManager->getDefinition($entity->getUpdateEntityType())->getLabel(); $row['id'] = $entity->id(); // You probably want a few more properties here... return $row + parent::buildRow($entity); }
/** * {@inheritdoc} */ protected function alterRoutes(RouteCollection $collection) { foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) { if ($route = $this->getRdfExportRoute($entity_type)) { $collection->add("entity.{$entity_type_id}.rdf_export", $route); $collection->add("entity.{$entity_type_id}.rdf_export_download", $this->getDownloadRoute($entity_type)); } } }
/** * Constructs a new instance. * * @param \Drupal\Core\Extension\ModuleHandlerInterface * The module handler. * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface * The event dispatcher. * @param \Drupal\Core\Config\TypedConfigManagerInterface $typed_config_manager * THe typed config manager. * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager * The entity type manager. */ public function __construct(ModuleHandlerInterface $module_handler, EventDispatcherInterface $event_dispatcher, TypedConfigManagerInterface $typed_config_manager, EntityTypeManagerInterface $entity_type_manager) { $this->currencyResourceRepository = new ResourceRepository(); $this->currencyStorage = $entity_type_manager->getStorage('currency'); $this->currencyLocaleStorage = $entity_type_manager->getStorage('currency_locale'); $this->eventDispatcher = $event_dispatcher; $this->moduleHandler = $module_handler; $this->typedConfigManager = $typed_config_manager; }
/** * Returns all continuous jobs with the given language. * * @param string $source_langcode * Source language. * * @return array * Array of continuous jobs. */ public function getContinuousJobs($source_langcode) { $jobs = array(); $ids = $this->entityTypeManager->getStorage('tmgmt_job')->getQuery()->condition('source_language', $source_langcode)->condition('job_type', Job::TYPE_CONTINUOUS)->condition('state', Job::STATE_CONTINUOUS)->execute(); if (!empty($ids)) { $jobs = Job::loadMultiple($ids); } return $jobs; }
/** * Constructs a new PriceDefaultWidget object. * * @param string $pluginId * The plugin_id for the widget. * @param mixed $pluginDefinition * The plugin implementation definition. * @param \Drupal\Core\Field\FieldDefinitionInterface $fieldDefinition * The definition of the field to which the widget is associated. * @param array $settings * The widget settings. * @param array $thirdPartySettings * Any third party settings. * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager * The entity type manager. * @param \Drupal\commerce_price\NumberFormatterFactoryInterface $numberFormatterFactory * The number formatter factory. */ public function __construct($pluginId, $pluginDefinition, FieldDefinitionInterface $fieldDefinition, array $settings, array $thirdPartySettings, EntityTypeManagerInterface $entityTypeManager, NumberFormatterFactoryInterface $numberFormatterFactory) { parent::__construct($pluginId, $pluginDefinition, $fieldDefinition, $settings, $thirdPartySettings); $this->currencyStorage = $entityTypeManager->getStorage('commerce_currency'); $this->numberFormatter = $numberFormatterFactory->createInstance(NumberFormatterInterface::DECIMAL); $this->numberFormatter->setMinimumFractionDigits(0); $this->numberFormatter->setMaximumFractionDigits(6); $this->numberFormatter->setGroupingUsed(FALSE); }
/** * {@inheritdoc} */ public function getFields($entity_type_id) { $entity_type = $this->entityTypeManager->getDefinition($entity_type_id); if (!$entity_type->isSubclassOf('\\Drupal\\Core\\Entity\\ContentEntityInterface')) { return []; } $map = $this->getAllFields(); return isset($map[$entity_type_id]) ? $map[$entity_type_id] : []; }
/** * {@inheritdoc} */ public function setUp() { $this->currencyStorage = $this->getMock(EntityStorageInterface::class); $this->currencyLocaleStorage = $this->getMock(EntityStorageInterface::class); $this->entityTypeManager = $this->getMock(EntityTypeManagerInterface::class); $map = [['currency', $this->currencyStorage], ['currency_locale', $this->currencyLocaleStorage]]; $this->entityTypeManager->expects($this->atLeastOnce())->method('getStorage')->willReturnMap($map); $this->stringTranslation = $this->getStringTranslationStub(); $this->sut = new FormHelper($this->stringTranslation, $this->entityTypeManager); }
/** * {@inheritdoc} */ protected function alterRoutes(RouteCollection $collection) { foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) { if ($devel_render = $entity_type->getLinkTemplate('token-devel')) { $options = ['_admin_route' => TRUE, '_token_entity_type_id' => $entity_type_id, 'parameters' => [$entity_type_id => ['type' => 'entity:' . $entity_type_id]]]; $route = new Route($devel_render, ['_controller' => '\\Drupal\\token\\Controller\\TokenDevelController::entityTokens', '_title' => 'Devel Tokens'], ['_permission' => 'access devel information', '_module_dependencies' => 'devel'], $options); $collection->add("entity.{$entity_type_id}.token_devel", $route); } } }
/** * {@inheritdoc} */ public function build() { /** @var \Drupal\Core\Entity\EntityInterface $group */ $group = $this->getContext('og')->getContextValue(); $view_builder = $this->entityTypeManager->getViewBuilder($group->getEntityTypeId()); // We render the related view mode only in this block. Additional modules, // like collection and solution, will add more elements directly. $build['group'] = $view_builder->view($group, 'group_header'); return $build; }