コード例 #1
0
ファイル: DemoBlock.php プロジェクト: Lullabot/challenge4
 /**
  * {@inheritdoc}
  */
 public function build()
 {
     $items = array();
     // When on a node page, the parameter is already upcast as a node.
     $node = \Drupal::routeMatch()->getParameter('node');
     if ($node) {
         // Read about entity query at http://www.sitepoint.com/drupal-8-version-entityfieldquery/.
         // See query API at https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Query%21QueryInterface.php/interface/QueryInterface/8.
         // The static method for using the query service would have been:
         // $query = \Drupal::entityQuery('node');
         // Use injected queryFactory to look for items that are related
         // to the show that matches the input nid.
         $query = $this->entity_query->get('node')->condition('status', 1)->condition('type', 'tv_episode')->sort('field_related_season.entity.field_season_number.value', 'DESC')->sort('field_episode_number', 'DESC')->range(0, 5)->condition('field_related_season.entity.field_related_show.entity.nid', $node->id());
         $nids = $query->execute();
         // Note that entity_load() is deprecated.
         // The static method of loading the entity would have been:
         // \Drupal\node\Entity\Node::load();
         // Use the injected entityManager to load the results into an array of node objects.
         $nodes = $this->entity_manager->getStorage('node')->loadMultiple($nids);
         foreach ($nodes as $node) {
             // Create a render array for each title field.
             // Note that field_view_field() is deprecated, use the view method on the field.
             $title = $node->title->view('full');
             // Entities have a handy toLink() method.
             $items[] = $node->toLink($title);
         }
     }
     // Return a render array for a html list.
     return ['#theme' => 'item_list', '#items' => $items, '#cache' => ['contexts' => ['route']]];
 }
コード例 #2
0
 /**
  * Say hello to the world.
  *
  * @return string
  *   Return "Hello world!" string.
  */
 public function helloWorld(EntityViewModeInterface $viewmode)
 {
     $content = ['#type' => 'markup', '#markup' => $this->t('Hello world!')];
     // Second version displaying the opening hours of the library.
     $opening_hours = $this->config('happy_alexandrie.library_config')->get('opening_hours');
     if (!empty($opening_hours)) {
         $content = ['#markup' => $this->t('<p>Greetings dear adventurer!</p><p>Opening hours:<br />@opening_hours</p>', array('@opening_hours' => $opening_hours))];
     }
     // Third version with the query
     // Query against our entities.
     $query = $this->query_factory->get('node')->condition('status', 1)->condition('type', 'alexandrie_book')->condition('changed', REQUEST_TIME, '<')->range(0, 5);
     $nids = $query->execute();
     if ($nids) {
         // Load the storage manager of our entity.
         $storage = $this->entity_manager->getStorage('node');
         // Now we can load the entities.
         $nodes = $storage->loadMultiple($nids);
         list($entity_type, $viewmode_name) = explode('.', $viewmode->getOriginalId());
         // Get the EntityViewBuilder instance.
         $render_controller = $this->entity_manager->getViewBuilder('node');
         $build = $render_controller->viewMultiple($nodes, $viewmode_name);
         $build['#markup'] = $this->t('Happy Query by view mode: @label', array('@label' => $viewmode->label()));
         $content[] = $build;
     } else {
         $content[] = array('#markup' => $this->t('No result'));
     }
     return $content;
 }
コード例 #3
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     $this->entityQuery = $this->getMockBuilder('Drupal\\Core\\Entity\\Query\\QueryInterface')->disableOriginalConstructor()->getMock();
     $this->entityQueryFactory = $this->getMockBuilder('Drupal\\Core\\Entity\\Query\\QueryFactory')->disableOriginalConstructor()->getMock();
     $this->entityQueryFactory->expects($this->any())->method('get')->will($this->returnValue($this->entityQuery));
     parent::setUp();
 }
コード例 #4
0
 /**
  * Generates IVW tracking information.
  *
  * @param EntityManagerInterface $entity_manager
  *   The entity query object for taxonomy terms.
  * @param QueryFactory $query
  *   The entity query object for taxonomy terms.
  * @param ConfigFactoryInterface $config_factory
  *   The config factory service.
  * @param PathMatcher $path_match
  *   The current path match.
  * @param CurrentRouteMatch $current_route_match
  *   The current route match.
  * @param Token $token
  *   Token service.
  */
 public function __construct(EntityManagerInterface $entity_manager, QueryFactory $query, ConfigFactoryInterface $config_factory, PathMatcher $path_match, CurrentRouteMatch $current_route_match, Token $token)
 {
     $this->termStorage = $entity_manager->getStorage('taxonomy_term');
     $this->nodeQuery = $query->get('node');
     $this->configFactory = $config_factory;
     $this->pathMatch = $path_match;
     $this->currentRouteMatch = $current_route_match;
     $this->token = $token;
 }
コード例 #5
0
 /**
  * Checks for an existing ECK entity type.
  *
  * @param string|int $entity_id
  *   The entity ID.
  * @param array $element
  *   The form element.
  * @param FormStateInterface $form_state
  *   The form state.
  *
  * @return bool
  *   TRUE if this format already exists, FALSE otherwise.
  */
 public function exists($entity_id, array $element, FormStateInterface $form_state)
 {
     // Use the query factory to build a new event entity query.
     $query = $this->entityQueryFactory->get('eck_entity_type');
     // Query the entity ID to see if its in use.
     $result = $query->condition('id', $element['#field_prefix'] . $entity_id)->execute();
     // We don't need to return the ID, only if it exists or not.
     return (bool) $result;
 }
コード例 #6
0
 /**
  * Constructor.
  *
  * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entityFieldManager
  *   The entity field manager.
  * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
  *   The event displatcher.
  * @param \Drupal\Core\Entity\Query\QueryFactory $query_factory
  *   The entity query factory.
  * @param \Drupal\Core\Database\Connection $connection
  *   The database connection.
  * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
  *   The config factory to get flippy settings.
  * @param \Drupal\Core\Utility\Token
  *   Drupal token service.
  * @param \Drupal\Core\Language\LanguageManager
  *   Drupal Language manager service.
  */
 public function __construct(EntityFieldManagerInterface $entityFieldManager, EventDispatcherInterface $event_dispatcher, QueryFactory $query_factory, Connection $connection, ConfigFactoryInterface $config_factory, Token $token, LanguageManager $languageManager)
 {
     $this->entityFieldManager = $entityFieldManager;
     $this->eventDispatcher = $event_dispatcher;
     $this->nodeQuery = $query_factory->get('node');
     $this->connection = $connection;
     $this->flippySettings = $config_factory->get('flippy.settings');
     $this->token = $token;
     $this->languageManager = $languageManager;
 }
コード例 #7
0
 /**
  * {@inheritdoc}
  */
 protected function interact(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $viewId = $input->getArgument('view-id');
     if (!$viewId) {
         $views = $this->entityQuery->get('view')->condition('status', 1)->execute();
         $viewId = $io->choiceNoList($this->trans('commands.views.debug.arguments.view-id'), $views);
         $input->setArgument('view-id', $viewId);
     }
 }
コード例 #8
0
ファイル: UserListBuilder.php プロジェクト: shumer/blog
 /**
  * {@inheritdoc}
  */
 public function load()
 {
     $entity_query = $this->queryFactory->get('user');
     $entity_query->condition('uid', 0, '<>');
     $entity_query->pager(50);
     $header = $this->buildHeader();
     $entity_query->tableSort($header);
     $uids = $entity_query->execute();
     return $this->storage->loadMultiple($uids);
 }
コード例 #9
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $blocks = $this->queryFactory->get('block_content')->condition('type', $this->entity->id())->execute();
     if (!empty($blocks)) {
         $caption = '<p>' . format_plural(count($blocks), '%label is used by 1 custom block on your site. You can not remove this block type until you have removed all of the %label blocks.', '%label is used by @count custom blocks on your site. You may not remove %label until you have removed all of the %label custom blocks.', array('%label' => $this->entity->label())) . '</p>';
         $form['description'] = array('#markup' => $caption);
         return $form;
     } else {
         return parent::buildForm($form, $form_state);
     }
 }
コード例 #10
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $num_nodes = $this->queryFactory->get('node')->condition('type', $this->entity->id())->count()->execute();
     if ($num_nodes) {
         $caption = '<p>' . format_plural($num_nodes, '%type is used by 1 piece of content on your site. You can not remove this content type until you have removed all of the %type content.', '%type is used by @count pieces of content on your site. You may not remove %type until you have removed all of the %type content.', array('%type' => $this->entity->label())) . '</p>';
         $form['#title'] = $this->getQuestion();
         $form['description'] = array('#markup' => $caption);
         return $form;
     }
     return parent::buildForm($form, $form_state);
 }
コード例 #11
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $product_count = $this->queryFactory->get('commerce_product')->condition('type', $this->entity->id())->count()->execute();
     if ($product_count) {
         $caption = '<p>' . $this->formatPlural($product_count, '%type is used by 1 product on your site. You can not remove this product type until you have removed all of the %type products.', '%type is used by @count products on your site. You may not remove %type until you have removed all of the %type products.', ['%type' => $this->entity->label()]) . '</p>';
         $form['#title'] = $this->getQuestion();
         $form['description'] = ['#markup' => $caption];
         return $form;
     }
     return parent::buildForm($form, $form_state);
 }
コード例 #12
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $num_profiles = $this->queryFactory->get('profile')->condition('type', $this->entity->id())->count()->execute();
     if ($num_profiles) {
         $caption = '<p>' . \Drupal::translation()->formatPlural($num_profiles, '%type is used by 1 profile on your site. You can not remove this profile type until you have removed all of the %type profiles.', '%type is used by @count profiles on your site. You may not remove %type until you have removed all of the %type profiles.', ['%type' => $this->entity->label()]) . '</p>';
         $form['#title'] = $this->entity->label();
         $form['description'] = ['#markup' => $caption];
         return $form;
     }
     return parent::buildForm($form, $form_state);
 }
コード例 #13
0
ファイル: Fid.php プロジェクト: neetumorwani/blogging
 /**
  * Override the behavior of titleQuery(). Get the filenames.
  */
 public function titleQuery()
 {
     $fids = $this->entityQuery->get('file')->condition('fid', $this->value, 'IN')->execute();
     $controller = $this->entityManager->getStorage('file');
     $files = $controller->loadMultiple($fids);
     $titles = array();
     foreach ($files as $file) {
         $titles[] = $file->getFilename();
     }
     return $titles;
 }
コード例 #14
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $num_support_tickets = $this->queryFactory->get('support_ticket')->condition('support_ticket_type', $this->entity->id())->count()->execute();
     if ($num_support_tickets) {
         $caption = '<p>' . $this->formatPlural($num_support_tickets, '%type is used by 1 ticket on your site. You can not remove this support ticket type until you have removed all of the %type tickets.', '%type is used by @count tickets on your site. You may not remove %type until you have removed all of the %type tickets.', array('%type' => $this->entity->label())) . '</p>';
         $form['#title'] = $this->getQuestion();
         $form['description'] = array('#markup' => $caption);
         return $form;
     }
     return parent::buildForm($form, $form_state);
 }
コード例 #15
0
ファイル: PageFormBase.php プロジェクト: neeravbm/unify-d8
 /**
  * {@inheritdoc}
  */
 public function validatePath(&$element, FormStateInterface $form_state)
 {
     // Ensure the path has a leading slash.
     $value = '/' . trim($element['#value'], '/');
     $form_state->setValueForElement($element, $value);
     // Ensure each path is unique.
     $path = $this->entityQuery->get('page')->condition('path', $value)->condition('id', $form_state->getValue('id'), '<>')->execute();
     if ($path) {
         $form_state->setErrorByName('path', $this->t('The page path must be unique.'));
     }
 }
コード例 #16
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $num_paragraphs = $this->queryFactory->get('paragraph')->condition('type', $this->entity->id())->count()->execute();
     if ($num_paragraphs) {
         $caption = '<p>' . $this->formatPlural($num_paragraphs, '%type Paragraphs type is used by 1 piece of content on your site. You can not remove this %type Paragraphs type until you have removed all from the content.', '%type Paragraphs type is used by @count pieces of content on your site. You may not remove %type Paragraphs type until you have removed all from the content.', ['%type' => $this->entity->label()]) . '</p>';
         $form['#title'] = $this->getQuestion();
         $form['description'] = ['#markup' => $caption];
         return $form;
     }
     return parent::buildForm($form, $form_state);
 }
コード例 #17
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     // Check if any entity of this type already exists.
     $content_number = $this->queryFactory->get($this->entity->getEntityType()->getBundleOf())->condition('type', $this->entity->id())->count()->execute();
     if (!empty($content_number)) {
         $warning_message = '<p>' . $this->formatPlural($content_number, '%type is used by 1 entity on your site. You can not remove this entity type until you have removed all of the %type entities.', '%type is used by @count entities on your site. You may not remove %type until you have removed all of the %type entities.', array('%type' => $this->entity->label())) . '</p>';
         $form['#title'] = $this->getQuestion();
         $form['description'] = array('#markup' => $warning_message);
         return $form;
     }
     return parent::buildForm($form, $form_state);
 }
コード例 #18
0
 /**
  * {@inheritdoc}
  */
 public function getDerivativeDefinitions($base_plugin_definition)
 {
     // Get all custom menu links which should be rediscovered.
     $entity_ids = $this->queryFactory->get('menu_link_content')->condition('rediscover', TRUE)->execute();
     $plugin_definitions = [];
     $menu_link_content_entities = $this->entityManager->getStorage('menu_link_content')->loadMultiple($entity_ids);
     /** @var \Drupal\menu_link_content\MenuLinkContentInterface $menu_link_content */
     foreach ($menu_link_content_entities as $menu_link_content) {
         $plugin_definitions[$menu_link_content->uuid()] = $menu_link_content->getPluginDefinition();
     }
     return $plugin_definitions;
 }
コード例 #19
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     // Get the custom entity ID.
     $custom_entity_id = $this->entity->getEntityType()->getBundleOf();
     $entities = $this->queryFactory->get($custom_entity_id)->condition('type', $this->entity->id())->execute();
     if (!empty($entities)) {
         $caption = '<p>' . $this->formatPlural(count($entities), '%label is used by 1 entity on your site. You can not remove this entity type until you have removed all of the %label entities.', '%label is used by @count entities on your site. You may not remove %label until you have removed all of the %label entities.', ['%label' => $this->entity->label()]) . '</p>';
         $form['description'] = array('#markup' => $caption);
         return $form;
     } else {
         return parent::buildForm($form, $form_state);
     }
 }
コード例 #20
0
 /**
  * Upgrade a whole bundle to use video_embed_field.
  *
  * @param \Drupal\media_entity\Entity\MediaBundle $bundle
  *   The media bundle object.
  */
 protected function upgradeBundle(MediaBundle $bundle)
 {
     // Create a video embed field on the media bundle.
     VideoEmbedField::createVideoEmbedField($bundle->id());
     // Load and update all of the existing media entities.
     $media_entities = $this->entityQuery->get('media')->condition('bundle', $bundle->id())->execute();
     foreach ($media_entities as $media_entity) {
         $media_entity = Media::load($media_entity);
         $this->upgradeEntity($media_entity, $bundle->getTypeConfiguration());
     }
     // Update the media bundle type.
     $bundle->type = 'video_embed_field';
     $bundle->save();
 }
コード例 #21
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $roles = $input->getOption('roles');
     $limit = $input->getOption('limit');
     $uids = $this->splitOption($input->getOption('uid'));
     $usernames = $this->splitOption($input->getOption('username'));
     $mails = $this->splitOption($input->getOption('mail'));
     $userStorage = $this->entityTypeManager->getStorage('user');
     $systemRoles = $this->drupalApi->getRoles();
     $query = $this->entityQuery->get('user');
     $query->condition('uid', 0, '>');
     $query->sort('uid');
     // uid as option
     if (is_array($uids) && $uids) {
         $group = $query->andConditionGroup()->condition('uid', $uids, 'IN');
         $query->condition($group);
     }
     // username as option
     if (is_array($usernames) && $usernames) {
         $group = $query->andConditionGroup()->condition('name', $usernames, 'IN');
         $query->condition($group);
     }
     // mail as option
     if (is_array($mails) && $mails) {
         $group = $query->andConditionGroup()->condition('mail', $mails, 'IN');
         $query->condition($group);
     }
     if ($roles) {
         $query->condition('roles', is_array($roles) ? $roles : [$roles], 'IN');
     }
     if ($limit) {
         $query->range(0, $limit);
     }
     $results = $query->execute();
     $users = $userStorage->loadMultiple($results);
     $tableHeader = [$this->trans('commands.user.debug.messages.user-id'), $this->trans('commands.user.debug.messages.username'), $this->trans('commands.user.debug.messages.roles'), $this->trans('commands.user.debug.messages.status')];
     $tableRows = [];
     foreach ($users as $userId => $user) {
         $userRoles = [];
         foreach ($user->getRoles() as $userRole) {
             $userRoles[] = $systemRoles[$userRole];
         }
         $status = $user->isActive() ? $this->trans('commands.common.status.enabled') : $this->trans('commands.common.status.disabled');
         $tableRows[] = [$userId, $user->getUsername(), implode(', ', $userRoles), $status];
     }
     $io->table($tableHeader, $tableRows);
 }
 /**
  * Tests the optimized node access checking.
  *
  * @covers ::checkNodeAccess
  * @covers ::collectNodeLinks
  * @covers ::checkAccess
  */
 public function testCheckNodeAccess()
 {
     $links = array(1 => MenuLinkMock::create(array('id' => 'node.1', 'route_name' => 'entity.node.canonical', 'title' => 'foo', 'parent' => '', 'route_parameters' => array('node' => 1))), 2 => MenuLinkMock::create(array('id' => 'node.2', 'route_name' => 'entity.node.canonical', 'title' => 'bar', 'parent' => '', 'route_parameters' => array('node' => 2))), 3 => MenuLinkMock::create(array('id' => 'node.3', 'route_name' => 'entity.node.canonical', 'title' => 'baz', 'parent' => 'node.2', 'route_parameters' => array('node' => 3))), 4 => MenuLinkMock::create(array('id' => 'node.4', 'route_name' => 'entity.node.canonical', 'title' => 'qux', 'parent' => 'node.3', 'route_parameters' => array('node' => 4))), 5 => MenuLinkMock::create(array('id' => 'test.1', 'route_name' => 'test_route', 'title' => 'qux', 'parent' => '')), 6 => MenuLinkMock::create(array('id' => 'test.2', 'route_name' => 'test_route', 'title' => 'qux', 'parent' => 'test.1')));
     $tree = array();
     $tree[1] = new MenuLinkTreeElement($links[1], FALSE, 1, FALSE, array());
     $tree[2] = new MenuLinkTreeElement($links[2], TRUE, 1, FALSE, array(3 => new MenuLinkTreeElement($links[3], TRUE, 2, FALSE, array(4 => new MenuLinkTreeElement($links[4], FALSE, 3, FALSE, array())))));
     $tree[5] = new MenuLinkTreeElement($links[5], TRUE, 1, FALSE, array(6 => new MenuLinkTreeElement($links[6], FALSE, 2, FALSE, array())));
     $query = $this->getMock('Drupal\\Core\\Entity\\Query\\QueryInterface');
     $query->expects($this->at(0))->method('condition')->with('nid', array(1, 2, 3, 4));
     $query->expects($this->at(1))->method('condition')->with('status', NODE_PUBLISHED);
     $query->expects($this->once())->method('execute')->willReturn(array(1, 2, 4));
     $this->queryFactory->expects($this->once())->method('get')->with('node')->willReturn($query);
     $node_access_result = AccessResult::allowed()->cachePerPermissions()->addCacheContexts(['user.node_grants:view']);
     $tree = $this->defaultMenuTreeManipulators->checkNodeAccess($tree);
     $this->assertEquals($node_access_result, $tree[1]->access);
     $this->assertEquals($node_access_result, $tree[2]->access);
     // Ensure that access denied is set.
     $this->assertEquals(AccessResult::neutral(), $tree[2]->subtree[3]->access);
     $this->assertEquals($node_access_result, $tree[2]->subtree[3]->subtree[4]->access);
     // Ensure that other routes than entity.node.canonical are set as well.
     $this->assertNull($tree[5]->access);
     $this->assertNull($tree[5]->subtree[6]->access);
     // On top of the node access checking now run the ordinary route based
     // access checkers.
     // Ensure that the access manager is just called for the non-node routes.
     $this->accessManager->expects($this->at(0))->method('checkNamedRoute')->with('test_route', [], $this->currentUser, TRUE)->willReturn(AccessResult::allowed());
     $this->accessManager->expects($this->at(1))->method('checkNamedRoute')->with('test_route', [], $this->currentUser, TRUE)->willReturn(AccessResult::neutral());
     $tree = $this->defaultMenuTreeManipulators->checkAccess($tree);
     $this->assertEquals($node_access_result, $tree[1]->access);
     $this->assertEquals($node_access_result, $tree[2]->access);
     $this->assertEquals(AccessResult::neutral(), $tree[2]->subtree[3]->access);
     $this->assertEquals(AccessResult::allowed()->cachePerPermissions(), $tree[5]->access);
     $this->assertEquals(AccessResult::neutral()->cachePerPermissions(), $tree[5]->subtree[6]->access);
 }
コード例 #23
0
 /**
  * Update a field. This is used to process fields when the storage
  * configuration changes.
  *
  * @param $entity_type
  * @param $field_name
  * @param string $op (encrypt / decrypt)
  */
 protected function update_stored_field($entity_type, $field_name, $op = 'encrypt')
 {
     /**
      * Before we load entities, we have to disable the encryption setting.
      * Otherwise, the act of loading the entity triggers an improper decryption
      * Which messes up the batch encryption.
      */
     $this->updatingStoredField = $field_name;
     /**
      * @var $query \Drupal\Core\Entity\Query\QueryInterface
      */
     $query = $this->queryFactory->get($entity_type);
     // The field is present.
     $query->exists($field_name);
     $query->allRevisions();
     $entity_ids = $query->execute();
     // Load entities.
     /**
      * @var $entity_storage \Drupal\Core\Entity\ContentEntityStorageBase
      */
     $entity_storage = $this->entityManager->getStorage($entity_type);
     foreach ($entity_ids as $revision_id => $entity_id) {
         /**
          * @var $entity \Drupal\Core\Entity\Entity
          */
         $entity = $entity_storage->loadRevision($revision_id);
         /**
          * @var $field \Drupal\Core\Field\FieldItemList
          */
         $field = $entity->get($field_name);
         $this->process_field($field, $op, TRUE);
         // Save the entity.
         $entity->save();
     }
 }
コード例 #24
0
 /**
  * Performs access checking for nodes in an optimized way.
  *
  * This manipulator should be added before the generic ::checkAccess() one,
  * because it provides a performance optimization for ::checkAccess().
  *
  * @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
  *   The menu link tree to manipulate.
  *
  * @return \Drupal\Core\Menu\MenuLinkTreeElement[]
  *   The manipulated menu link tree.
  */
 public function checkNodeAccess(array $tree)
 {
     $node_links = array();
     $this->collectNodeLinks($tree, $node_links);
     if ($node_links) {
         $nids = array_keys($node_links);
         $query = $this->queryFactory->get('node');
         $query->condition('nid', $nids, 'IN');
         // Allows admins to view all nodes, by both disabling node_access
         // query rewrite as well as not checking for the node status. The
         // 'view own unpublished nodes' permission is ignored to not require cache
         // entries per user.
         $access_result = AccessResult::allowed()->cachePerPermissions();
         if ($this->account->hasPermission('bypass node access')) {
             $query->accessCheck(FALSE);
         } else {
             $access_result->addCacheContexts(['user.node_grants:view']);
             $query->condition('status', NODE_PUBLISHED);
         }
         $nids = $query->execute();
         foreach ($nids as $nid) {
             foreach ($node_links[$nid] as $key => $link) {
                 $node_links[$nid][$key]->access = $access_result;
             }
         }
     }
     return $tree;
 }
コード例 #25
0
 /**
  * {@inheritdoc}
  */
 public function getCountNewComments(EntityInterface $entity, $field_name = NULL, $timestamp = 0)
 {
     // @todo Replace module handler with optional history service injection
     //   after http://drupal.org/node/2081585
     if ($this->currentUser->isAuthenticated() && $this->moduleHandler->moduleExists('history')) {
         // Retrieve the timestamp at which the current user last viewed this entity.
         if (!$timestamp) {
             if ($entity->getEntityTypeId() == 'node') {
                 $timestamp = history_read($entity->id());
             } else {
                 $function = $entity->getEntityTypeId() . '_last_viewed';
                 if (function_exists($function)) {
                     $timestamp = $function($entity->id());
                 } else {
                     // Default to 30 days ago.
                     // @todo Remove once http://drupal.org/node/1029708 lands.
                     $timestamp = COMMENT_NEW_LIMIT;
                 }
             }
         }
         $timestamp = $timestamp > HISTORY_READ_LIMIT ? $timestamp : HISTORY_READ_LIMIT;
         // Use the timestamp to retrieve the number of new comments.
         $query = $this->queryFactory->get('comment')->condition('entity_type', $entity->getEntityTypeId())->condition('entity_id', $entity->id())->condition('created', $timestamp, '>')->condition('status', CommentInterface::PUBLISHED);
         if ($field_name) {
             // Limit to a particular field.
             $query->condition('field_name', $field_name);
         }
         return $query->count()->execute();
     }
     return FALSE;
 }
コード例 #26
0
ファイル: ContentEntityNormalizer.php プロジェクト: WChoy/hme
 /**
  * Implements \Symfony\Component\Serializer\Normalizer\NormalizerInterface::normalize()
  */
 public function normalize($entity, $format = NULL, array $context = array())
 {
     // Create the array of normalized fields, starting with the URI.
     /** @var $entity \Drupal\Core\Entity\ContentEntityInterface */
     $normalized = array("class" => array(), "properties" => array(), "entities" => array(), "actions" => array(), "links" => array(array("rel" => array("self"), "href" => $this->getEntityUri($entity))));
     $mapper = null;
     $query = $this->queryFactory->get('siren_mapper')->condition('entityType', $entity->getEntityTypeId())->condition('bundleType', $entity->bundle());
     $ids = $query->execute();
     if (isset($ids)) {
         $mapper = entity_load('siren_mapper', array_keys($ids)[0]);
     }
     // Get the fields to include
     $map_fields = array();
     // If we have a mapper
     if ($mapper) {
         $normalized['class'] = $mapper->classes;
         foreach ($mapper->fieldMappings as $mapping) {
             $map_fields[] = $mapping['fieldName'];
         }
     }
     $fields = $entity->getProperties();
     // Ignore the entity ID and revision ID.
     $exclude = array($entity->getEntityType()->getKey('id'), $entity->getEntityType()->getKey('revision'));
     foreach ($fields as $field) {
         if (in_array($field->getFieldDefinition()->getName(), $exclude)) {
             continue;
         }
         if (!in_array($field->getName(), $map_fields)) {
             continue;
         }
         $normalized_property = $this->serializer->normalize($field, $format, $context);
         $normalized = NestedArray::mergeDeep($normalized, $normalized_property);
     }
     return $normalized;
 }
コード例 #27
0
 /**
  * Tests querying.
  */
 public function testQuery()
 {
     // This returns the 0th entity as that's only one pointing to the 0th
     // account.
     $this->queryResults = $this->factory->get('entity_test')->condition("user_id.entity.name", $this->accounts[0]->getUsername())->execute();
     $this->assertResults(array(0));
     // This returns the 1st and 2nd entity as those point to the 1st account.
     $this->queryResults = $this->factory->get('entity_test')->condition("user_id.entity.name", $this->accounts[0]->getUsername(), '<>')->execute();
     $this->assertResults(array(1, 2));
     // This returns all three entities because all of them point to an
     // account.
     $this->queryResults = $this->factory->get('entity_test')->exists("user_id.entity.name")->execute();
     $this->assertResults(array(0, 1, 2));
     // This returns no entities because all of them point to an account.
     $this->queryResults = $this->factory->get('entity_test')->notExists("user_id.entity.name")->execute();
     $this->assertEqual(count($this->queryResults), 0);
     // This returns the 0th entity as that's only one pointing to the 0th
     // term (test without specifying the field column).
     $this->queryResults = $this->factory->get('entity_test')->condition("{$this->fieldName}.entity.name", $this->terms[0]->name->value)->execute();
     $this->assertResults(array(0));
     // This returns the 0th entity as that's only one pointing to the 0th
     // term (test with specifying the column name).
     $this->queryResults = $this->factory->get('entity_test')->condition("{$this->fieldName}.target_id.entity.name", $this->terms[0]->name->value)->execute();
     $this->assertResults(array(0));
     // This returns the 1st and 2nd entity as those point to the 1st term.
     $this->queryResults = $this->factory->get('entity_test')->condition("{$this->fieldName}.entity.name", $this->terms[0]->name->value, '<>')->execute();
     $this->assertResults(array(1, 2));
 }
 /**
  * Carries out entity bundle deletion and deletes entities of this type.
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     // Find all the entities of this type, using an entity query.
     $query = $this->queryFactory->get('myentity');
     $query->condition('subtype', $this->entity->id());
     $ids = $query->execute();
     // Delete the found entities, using the storage controller.
     // You may actually need to use a batch here, if there could be
     // many entities.
     $storage = $this->manager->getStorage('myentity');
     $entities = $storage->loadMultiple($ids);
     $storage->delete($entities);
     // Delete the bundle entity itself.
     $this->entity->delete();
     $form_state->setRedirectUrl($this->getCancelUrl());
 }
コード例 #29
0
 /**
  * @param string $url_name URL Product Name
  * @return mixed|NULL
  */
 private function findProduct($url_name)
 {
     $query = $this->entityQuery->get('node', 'AND');
     $query->condition('field_url_product_name', $url_name);
     $nid = current($query->execute());
     return Node::load($nid);
 }
コード例 #30
0
ファイル: MenuForm.php プロジェクト: alnutile/drunatra
 /**
  * Form constructor to edit an entire menu tree at once.
  *
  * Shows for one menu the menu links accessible to the current user and
  * relevant operations.
  *
  * This form constructor can be integrated as a section into another form. It
  * relies on the following keys in $form_state:
  * - menu: A menu entity.
  * - menu_overview_form_parents: An array containing the parent keys to this
  *   form.
  * Forms integrating this section should call menu_overview_form_submit() from
  * their form submit handler.
  */
 protected function buildOverviewForm(array &$form, array &$form_state)
 {
     // Ensure that menu_overview_form_submit() knows the parents of this form
     // section.
     $form['#tree'] = TRUE;
     $form['#theme'] = 'menu_overview_form';
     $form_state += array('menu_overview_form_parents' => array());
     $form['#attached']['css'] = array(drupal_get_path('module', 'menu') . '/css/menu.admin.css');
     $links = array();
     $query = $this->entityQueryFactory->get('menu_link')->condition('menu_name', $this->entity->id());
     for ($i = 1; $i <= MENU_MAX_DEPTH; $i++) {
         $query->sort('p' . $i, 'ASC');
     }
     $result = $query->execute();
     if (!empty($result)) {
         $links = $this->menuLinkStorage->loadMultiple($result);
     }
     $delta = max(count($links), 50);
     // We indicate that a menu administrator is running the menu access check.
     $this->getRequest()->attributes->set('_menu_admin', TRUE);
     $tree = $this->menuTree->buildTreeData($links);
     $this->getRequest()->attributes->set('_menu_admin', FALSE);
     $form = array_merge($form, $this->buildOverviewTreeForm($tree, $delta));
     $form['#empty_text'] = t('There are no menu links yet. <a href="@link">Add link</a>.', array('@link' => url('admin/structure/menu/manage/' . $this->entity->id() . '/add')));
     return $form;
 }