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];
 }
 /**
  * {@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}
  */
 protected function interact(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     // --module option
     $module = $input->getOption('module');
     if (!$module) {
         // @see Drupal\Console\Command\Shared\ModuleTrait::moduleQuestion
         $module = $this->moduleQuestion($io);
         $input->setOption('module', $module);
     }
     // view-id argument
     $viewId = $input->getArgument('view-id');
     if (!$viewId) {
         $views = $this->entityTypeManager->getStorage('view')->loadMultiple();
         $viewList = [];
         foreach ($views as $view) {
             $viewList[$view->get('id')] = $view->get('label');
         }
         $viewId = $io->choiceNoList($this->trans('commands.config.export.view.questions.view'), $viewList);
         $input->setArgument('view-id', $viewId);
     }
     $optionalConfig = $input->getOption('optional-config');
     if (!$optionalConfig) {
         $optionalConfig = $io->confirm($this->trans('commands.config.export.view.questions.optional-config'), true);
         $input->setOption('optional-config', $optionalConfig);
     }
     $includeModuleDependencies = $input->getOption('include-module-dependencies');
     if (!$includeModuleDependencies) {
         $includeModuleDependencies = $io->confirm($this->trans('commands.config.export.view.questions.include-module-dependencies'), true);
         $input->setOption('include-module-dependencies', $includeModuleDependencies);
     }
 }
 /**
  * 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();
 }
示例#5
0
 /**
  * {@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;
 }
示例#7
0
 /**
  * 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');
 }
示例#8
0
 /**
  * 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);
 }
 /**
  * {@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);
 }
 /**
  * {@inheritdoc}
  */
 public function form(array $form, FormStateInterface $form_state)
 {
     /* @var \Drupal\Core\Config\Entity\ConfigEntityTypeInterface $bundle */
     $bundle = $form_state->getFormObject()->getEntity();
     $form['enable_moderation_state'] = ['#type' => 'checkbox', '#title' => $this->t('Enable moderation states.'), '#description' => $this->t('Content of this type must transition through moderation states in order to be published.'), '#default_value' => $bundle->getThirdPartySetting('content_moderation', 'enabled', FALSE)];
     // Add a special message when moderation is being disabled.
     if ($bundle->getThirdPartySetting('content_moderation', 'enabled', FALSE)) {
         $form['enable_moderation_state_note'] = ['#type' => 'item', '#description' => $this->t('After disabling moderation, any existing forward drafts will be accessible via the "Revisions" tab.'), '#states' => ['visible' => [':input[name=enable_moderation_state]' => ['checked' => FALSE]]]];
     }
     $states = $this->entityTypeManager->getStorage('moderation_state')->loadMultiple();
     $label = function (ModerationState $state) {
         return $state->label();
     };
     $options_published = array_map($label, array_filter($states, function (ModerationState $state) {
         return $state->isPublishedState();
     }));
     $options_unpublished = array_map($label, array_filter($states, function (ModerationState $state) {
         return !$state->isPublishedState();
     }));
     $form['allowed_moderation_states_unpublished'] = ['#type' => 'checkboxes', '#title' => $this->t('Allowed moderation states (Unpublished)'), '#description' => $this->t('The allowed unpublished moderation states this content-type can be assigned.'), '#default_value' => $bundle->getThirdPartySetting('content_moderation', 'allowed_moderation_states', array_keys($options_unpublished)), '#options' => $options_unpublished, '#required' => TRUE, '#states' => ['visible' => [':input[name=enable_moderation_state]' => ['checked' => TRUE]]]];
     $form['allowed_moderation_states_published'] = ['#type' => 'checkboxes', '#title' => $this->t('Allowed moderation states (Published)'), '#description' => $this->t('The allowed published moderation states this content-type can be assigned.'), '#default_value' => $bundle->getThirdPartySetting('content_moderation', 'allowed_moderation_states', array_keys($options_published)), '#options' => $options_published, '#required' => TRUE, '#states' => ['visible' => [':input[name=enable_moderation_state]' => ['checked' => TRUE]]]];
     // The key of the array needs to be a user-facing string so we have to fully
     // render the translatable string to a real string, or else PHP errors on an
     // object used as an array key.
     $options = [$this->t('Unpublished')->render() => $options_unpublished, $this->t('Published')->render() => $options_published];
     $form['default_moderation_state'] = ['#type' => 'select', '#title' => $this->t('Default moderation state'), '#options' => $options, '#description' => $this->t('Select the moderation state for new content'), '#default_value' => $bundle->getThirdPartySetting('content_moderation', 'default_moderation_state', 'draft'), '#states' => ['visible' => [':input[name=enable_moderation_state]' => ['checked' => TRUE]]]];
     $form['#entity_builders'][] = [$this, 'formBuilderCallback'];
     return parent::form($form, $form_state);
 }
 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;
 }
 /**
  * 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();
             }
         }
     }
 }
 protected function getConfigNames($config_type)
 {
     // For a given entity type, load all entities.
     if ($config_type && $config_type !== 'system.simple') {
         $entity_storage = $this->entityTypeManager->getStorage($config_type);
         foreach ($entity_storage->loadMultiple() as $entity) {
             $entity_id = $entity->id();
             $label = $entity->label() ?: $entity_id;
             $names[$entity_id] = $label;
         }
     } else {
         // Gather the config entity prefixes.
         $config_prefixes = array_map(function ($definition) {
             return $definition->getConfigPrefix() . '.';
         }, $this->definitions);
         // Find all config, and then filter our anything matching a config prefix.
         $names = $this->configStorage->listAll();
         $names = array_combine($names, $names);
         foreach ($names as $config_name) {
             foreach ($config_prefixes as $config_prefix) {
                 if (strpos($config_name, $config_prefix) === 0) {
                     unset($names[$config_name]);
                 }
             }
         }
     }
     return $names;
 }
  /**
   * {@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());
 }
示例#16
0
 /**
  * {@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());
 }
 /**
  * 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;
 }
 /**
  * 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;
 }
示例#19
0
 /**
  * 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;
 }
示例#20
0
 /**
  * {@inheritdoc}
  */
 public function getDerivativeDefinitions($base_plugin_definition)
 {
     $this->derivatives = [];
     // Starting weight for ordering the local tasks.
     $weight = 10;
     foreach ($this->entityTypeManager->getStorage('profile_type')->loadMultiple() as $profile_type_id => $profile_type) {
         $this->derivatives["profile.type.{$profile_type_id}"] = ['title' => $profile_type->label(), 'route_name' => "entity.profile.type.{$profile_type_id}.user_profile_form", 'base_route' => 'entity.user.canonical', 'route_parameters' => ['profile_type' => $profile_type_id], 'weight' => ++$weight] + $base_plugin_definition;
     }
     return $this->derivatives;
 }
 /**
  * Tests Rules default components.
  */
 public function testDefaultComponents()
 {
     $config_entity = $this->storage->load('rules_test_default_component');
     $user = $this->entityTypeManager->getStorage('user')->create(['mail' => '*****@*****.**']);
     $config_entity->getComponent()->setContextValue('user', $user)->execute();
     // Test that the action was executed correctly.
     $messages = drupal_get_messages();
     $message_string = isset($messages['status'][0]) ? (string) $messages['status'][0] : NULL;
     $this->assertEquals($message_string, '*****@*****.**');
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $imageStyle = $this->entityTypeManager->getStorage('image_style');
     $io->newLine();
     $io->comment($this->trans('commands.image.styles.debug.messages.styles-list'));
     if ($imageStyle) {
         $this->imageStyleList($io, $imageStyle);
     }
     return 0;
 }
示例#23
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $uid = $input->getArgument('user-id');
     $user = $this->entityTypeManager->getStorage('user')->load($uid);
     if (!$user) {
         $io->error(sprintf($this->trans('commands.user.login.url.errors.invalid-user'), $uid));
         return 1;
     }
     $url = user_pass_reset_url($user);
     $io->success(sprintf($this->trans('commands.user.login.url.messages.url'), $user->getUsername(), $url));
 }
示例#24
0
 /**
  * {@inheritdoc}
  */
 public function onBundleDelete($bundle, $entity_type_id)
 {
     $this->entityTypeBundleInfo->clearCachedBundles();
     // Notify the entity storage.
     $storage = $this->entityTypeManager->getStorage($entity_type_id);
     if ($storage instanceof EntityBundleListenerInterface) {
         $storage->onBundleDelete($bundle, $entity_type_id);
     }
     // Invoke hook_entity_bundle_delete() hook.
     $this->moduleHandler->invokeAll('entity_bundle_delete', [$entity_type_id, $bundle]);
     $this->entityFieldManager->clearCachedFieldDefinitions();
 }
示例#25
0
  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);
    $lineItemType = $this->entity;
    // Prepare the list of purchasable entity types.
    $entityTypes = $this->entityTypeManager->getDefinitions();
    $purchasableEntityTypes = array_filter($entityTypes, function ($entityType) {
      return $entityType->isSubclassOf('\Drupal\commerce\PurchasableEntityInterface');
    });
    $purchasableEntityTypes = array_map(function ($entityType) {
      return $entityType->getLabel();
    }, $purchasableEntityTypes);
    // Prepare the list of order types.
    $orderTypes = $this->entityTypeManager->getStorage('commerce_order_type')
      ->loadMultiple();
    $orderTypes = array_map(function ($orderType) {
      return $orderType->label();
    }, $orderTypes);

    $form['label'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Label'),
      '#maxlength' => 255,
      '#default_value' => $lineItemType->label(),
      '#description' => $this->t('Label for the line item type.'),
      '#required' => TRUE,
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#default_value' => $lineItemType->id(),
      '#machine_name' => [
        'exists' => '\Drupal\commerce_order\Entity\LineItemType::load',
        'source' => ['label'],
      ],
      '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
    ];
    $form['purchasableEntityType'] = [
      '#type' => 'select',
      '#title' => $this->t('Purchasable entity type'),
      '#default_value' => $lineItemType->getPurchasableEntityType(),
      '#options' => $purchasableEntityTypes,
      '#empty_value' => '',
      '#disabled' => !$lineItemType->isNew(),
    ];
    $form['orderType'] = [
      '#type' => 'select',
      '#title' => $this->t('Order type'),
      '#default_value' => $lineItemType->getOrderType(),
      '#options' => $orderTypes,
      '#required' => TRUE,
    ];

    return $this->protectBundleIdElement($form);
  }
 /**
  * {@inheritdoc}
  */
 public function listTopics()
 {
     /** @var \Drupal\tour\TourInterface[] $tours */
     $tours = $this->entityTypeManager->getStorage('tour')->loadMultiple();
     // Sort in the manner defined by Tour.
     uasort($tours, ['Drupal\\tour\\Entity\\Tour', 'sort']);
     // Make a link to each tour, using the first of its routes that can
     // be linked to by this user, if any.
     $topics = [];
     foreach ($tours as $tour) {
         $title = $tour->label();
         $id = $tour->id();
         $routes = $tour->getRoutes();
         $made_link = FALSE;
         foreach ($routes as $route) {
             // Some tours are for routes with parameters. For instance, there is
             // currently a tour in the Language module for the language edit page,
             // which appears on all pages with URLs like:
             // /admin/config/regional/language/edit/LANGCODE.
             // There is no way to make a link to the page that displays the tour,
             // because it is a set of pages. The easiest way to detect this is to
             // use a try/catch exception -- try to make a link, and it will error
             // out with a missing parameter exception if the route leads to a set
             // of pages instead of a single page.
             try {
                 $params = isset($route['route_params']) ? $route['route_params'] : [];
                 $url = Url::fromRoute($route['route_name'], $params);
                 // Skip this route if the current user cannot access it.
                 if (!$url->access()) {
                     continue;
                 }
                 // Generate the link HTML directly, using toString(), to catch
                 // missing parameter exceptions now instead of at render time.
                 $topics[$id] = Link::fromTextAndUrl($title, $url)->toString();
                 // If the line above didn't generate an exception, we have a good
                 // link that the user can access.
                 $made_link = TRUE;
                 break;
             } catch (\Exception $e) {
                 // Exceptions are normally due to routes that need parameters. If
                 // there is an exception, just try the next route and see if we can
                 // find one that will work for us.
             }
         }
         if (!$made_link) {
             // None of the routes worked to make a link, so at least display the
             // tour title.
             $topics[$id] = $title;
         }
     }
     return $topics;
 }
示例#27
0
  /**
   * {@inheritdoc}
   */
  public function getDerivativeDefinitions($base_plugin_definition) {
    $this->derivatives = [];
    foreach ($this->entityTypeManager->getStorage('profile_type')->loadMultiple() as $profile_type_id => $profile_type) {
      $this->derivatives["profile.type.$profile_type_id"] = [
          'title' => $profile_type->label(),
          'route_name' => "entity.profile.type.$profile_type_id.user_profile_form",
          'parent_id' => 'entity.user.edit_form',
          'route_parameters' => ['profile_type' => $profile_type_id],
        ] + $base_plugin_definition;
    }

    return $this->derivatives;
  }
示例#28
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $entityDefinitionID = $input->getArgument('entity-definition-id');
     $entityID = $input->getArgument('entity-id');
     try {
         $this->entityTypeManager->getStorage($entityDefinitionID)->load($entityID)->delete();
     } catch (\Exception $e) {
         $io->error($e->getMessage());
         return 1;
     }
     $io->success(sprintf($this->trans('commands.entity.delete.messages.deleted'), $entityDefinitionID, $entityID));
 }
示例#29
0
 /**
  * {@inheritdoc}
  */
 public function loadEntityByConfigTarget($entity_type_id, $target)
 {
     $entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
     // For configuration entities, the config target is given by the entity ID.
     // @todo Consider adding a method to allow entity types to indicate the
     //   target identifier key rather than hard-coding this check. Issue:
     //   https://www.drupal.org/node/2412983.
     if ($entity_type instanceof ConfigEntityTypeInterface) {
         $entity = $this->entityTypeManager->getStorage($entity_type_id)->load($target);
     } else {
         $entity = $this->loadEntityByUuid($entity_type_id, $target);
     }
     return $entity;
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->panelsDisplay = $this->prophesize(PanelsDisplayVariant::class);
     $this->pageVariant = $this->prophesize(PageVariantInterface::class);
     $this->pageVariant->getVariantPlugin()->willReturn($this->panelsDisplay->reveal());
     $this->pageVariantNotPanels = $this->prophesize(PageVariantInterface::class);
     $this->pageVariantNotPanels->getContexts()->shouldNotBeCalled();
     $non_panels_variant = $this->prophesize(HttpStatusCodeDisplayVariant::class);
     $this->pageVariantNotPanels->getVariantPlugin()->willReturn($non_panels_variant->reveal());
     $this->storage = $this->prophesize(EntityStorageInterface::class);
     $this->entityTypeManager = $this->prophesize(EntityTypeManagerInterface::class);
     $this->entityTypeManager->getStorage('page_variant')->willReturn($this->storage->reveal());
 }