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; }
/** * {@inheritdoc} */ public function cloneEntity(EntityInterface $entity, EntityInterface $cloned_entity, $properties = []) { /** @var \Drupal\core\Config\Entity\ConfigEntityInterface $cloned_entity */ $id_key = $this->entityTypeManager->getDefinition($this->entityTypeId)->getKey('id'); $label_key = $this->entityTypeManager->getDefinition($this->entityTypeId)->getKey('label'); // Set new entity properties. if (isset($properties['id'])) { if ($id_key) { $cloned_entity->set($id_key, $properties['id']); } unset($properties['id']); } if (isset($properties['label'])) { if ($label_key) { $cloned_entity->set($label_key, $properties['label']); } unset($properties['label']); } foreach ($properties as $key => $property) { $cloned_entity->set($key, $property); } $cloned_entity->save(); return $cloned_entity; }
/** * On workflow transition. * * @param \Drupal\state_machine\Event\StateChangeEvent $event * The state change event. * * @throws \Drupal\message_notify\Exception\MessageNotifyException */ public function onChangeToValidated(StateChangeEvent $event) { $entity = $event->getEntity(); $bundle = $entity->bundle(); if ($bundle != 'solution') { return; } $message_template = MessageTemplate::load('workflow_transition'); $storage = $this->entityTypeManager->getStorage('og_membership'); // Sent a message to all solution administrators. $membership_query = $storage->getQuery()->condition('state', 'active')->condition('entity_id', $entity->id()); $memberships_ids = $membership_query->execute(); $memberships = OgMembership::loadMultiple($memberships_ids); $memberships = array_filter($memberships, function ($membership) { return $membership->hasPermission('message notification on validate'); }); /** @var OgMembership $membership */ foreach ($memberships as $membership) { $uid = $membership->get('uid')->first()->getValue()['target_id']; // Create the actual message and save it to the db. $message = Message::create(['template' => $message_template->id(), 'uid' => $uid, 'field_message_content' => $entity->id()]); $message->save(); // Send the saved message as an e-mail. $this->messageNotifier->send($message, [], 'email'); } }
/** * {@inheritdoc} */ public function cloneEntity(EntityInterface $entity, EntityInterface $cloned_entity, $properties = []) { /** @var \Drupal\core\Entity\ContentEntityInterface $cloned_entity */ if ($label_key = $this->entityTypeManager->getDefinition($this->entityTypeId)->getKey('label')) { $cloned_entity->set($label_key, $entity->label() . ' - Cloned'); } $cloned_entity->save(); return $cloned_entity; }
/** * Create node and populate fields. * * @param string $title * @param array $fields * @param string $type * @param int $uid */ public function createNode($title = '', $fields = [], $type = 'video', $uid = 1) { $node = $this->entity_type_manager->getStorage('node')->create(['type' => $type, 'title' => $title, 'uid' => $uid]); foreach ($fields as $field => $value) { $node->set($field, $value); } $node->save(); }
/** * {@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)); }
/** * {@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)); }
/** * {@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 deleteTemporaryAssets() when the config item for age is 0. * * @covers ::deleteTemporaryAssets * * @test */ public function deleteTemporaryAssetsDeletesAssetsWhenAgeIsGreaterThanZero() { $mock_config = $this->getMockBuilder(ImmutableConfig::class)->disableOriginalConstructor()->getMock(); $age = 123456; $mock_config->expects($this->once())->method('get')->with('temporary_maximum_age')->willReturn($age); $this->configFactory->expects($this->once())->method('get')->with('system.file')->willReturn($mock_config); $mock_query = $this->getMock('\\Drupal\\Core\\Entity\\Query\\QueryInterface'); $map = [['status', FILE_STATUS_PERMANENT, '<>'], ['changed', MOCK_TIMESTAMP - $age, '<']]; $mock_query->expects($this->exactly(2))->method('condition')->will($this->returnValueMap($map)); $mock_query->expects($this->once())->method('range')->with(0, 50)->will($this->returnSelf()); $mock_asset_ids = [123, 456, 789]; $mock_asset_ids = array_combine($mock_asset_ids, $mock_asset_ids); $mock_query->expects($this->once())->method('execute')->willReturn($mock_asset_ids); $mock_entity_storage = $this->getMock(EntityStorageInterface::class); $mock_entity_storage->expects($this->once())->method('getQuery')->willReturn($mock_query); $mock_assets = []; $log_map = []; foreach ($mock_asset_ids as $id) { $mock_asset = $this->getMockBuilder('\\Drupal\\embridge\\EmbridgeAssetEntityInterface')->disableOriginalConstructor()->getMock(); $mock_asset->expects($this->once())->method('delete'); $filename = 'Mock Asset ' . $id; $mock_asset->expects($this->once())->method('getFilename')->willReturn($filename); $mock_asset->expects($this->once())->method('id')->willReturn($id); $log_map[] = ['Embridge Asset "%filename" [%id] garbage collected during cron.', ['%filename' => $filename, '%id' => $id]]; $mock_assets[$id] = $mock_asset; } $this->logger->expects($this->exactly(count($mock_asset_ids)))->method('notice')->will($this->returnValueMap($log_map)); $mock_entity_storage->expects($this->once())->method('loadMultiple')->with($mock_asset_ids)->willReturn($mock_assets); $this->entityTypeManager->expects($this->once())->method('getStorage')->with('embridge_asset_entity')->willReturn($mock_entity_storage); $this->emdbHelper->deleteTemporaryAssets(); }
/** * Sets up all of our services with mock methods so buildForm() is possible. * * @param string $catalog_id * Catalog id. * @param string $application_id * Application id. * @param [] $filters * An optional list of filters for the client to receive. */ protected function baseMockBuild($catalog_id, $application_id, $filters = []) { // Field manager mocking. $field_settings = ['max_filesize' => '2 MB', 'file_extensions' => self::MOCK_FIELD_SETTINGS_FILE_EXTENSIONS, 'catalog_id' => $catalog_id]; $this->fieldConfig->expects($this->once())->method('getName')->willReturn('field_test'); $this->fieldConfig->expects($this->once())->method('getSettings')->willReturn($field_settings); // Search filter always starts with the extensions OR filter. $extension_filter_value = str_replace(',', '|', self::MOCK_FIELD_SETTINGS_FILE_EXTENSIONS); $extension_filter = ['field' => 'fileformat', 'operator' => 'matches', 'value' => $extension_filter_value]; array_unshift($filters, $extension_filter); // Client mocking. $search_response = $this->json->decode(file_get_contents('expected/search-expected-small-response.json', TRUE)); $per_page = 8; $page = 1; $this->client->expects($this->once())->method('search')->with($page, $per_page, $filters)->willReturn($search_response); // Entity type storage mocking. $mock_catalog = $this->getMockBuilder('\\Drupal\\embridge\\EmbridgeCatalogInterface')->disableOriginalConstructor()->getMock(); $mock_catalog->expects($this->once())->method('getApplicationId')->willReturn($application_id); $mock_catalog_storage = $this->getMock(EntityStorageInterface::class); $mock_catalog_storage->expects($this->once())->method('load')->with($catalog_id)->willReturn($mock_catalog); $this->entityTypeManager->expects($this->once())->method('getStorage')->with('embridge_catalog')->willReturn($mock_catalog_storage); // Create mock assets. foreach ($search_response['results'] as $i => $result) { $mock_asset = $this->getMockBuilder('\\Drupal\\embridge\\EmbridgeAssetEntityInterface')->disableOriginalConstructor()->getMock(); $mock_asset->expects($this->once())->method('id')->willReturn($i); $this->mockAssets[$i]['asset'] = $mock_asset; $this->mockAssets[$i]['result'] = $result; } // Mock up the asset helper. $return_map = []; foreach ($this->mockAssets as $id => $asset_result) { $return_map[] = [$asset_result['result'], $catalog_id, $asset_result['asset']]; } $this->assetHelper->expects($this->exactly(count($this->mockAssets)))->method('searchResultToAsset')->will($this->returnValueMap($return_map)); }
/** * Test submitForm with an fid, ensures values are set correctly. * * @covers ::ajaxSave * * @test */ public function ajaxSaveWithFidLoadsEntitiesAndSetsFormStateValues() { $form = []; $catalog_id = 'test_catalog'; $app_id = 'test_application_id'; $source_url = 'www.example.com/test_application_id/test.jpg'; $form['asset']['#catalog_id'] = $catalog_id; $form_state = new FormState(); $intial_values = ['asset' => [self::MOCK_ASSET_ID], 'attributes' => ['data-conversion' => 'thumb']]; $form_state->setValues($intial_values); $mock_asset = $this->getMockBuilder(EmbridgeAssetEntity::class)->disableOriginalConstructor()->getMock(); $mock_asset->expects($this->once())->method('uuid')->willReturn(self::MOCK_ASSET_UUID); $mock_asset->expects($this->once())->method('isTemporary')->willReturn(TRUE); $mock_asset->expects($this->once())->method('setPermanent'); $mock_asset->expects($this->once())->method('save'); $mock_asset_storage = $this->getMockBuilder(EntityStorageInterface::class)->disableOriginalConstructor()->getMock(); $mock_asset_storage->expects($this->once())->method('load')->with(self::MOCK_ASSET_ID)->willReturn($mock_asset); $mock_catalog = $this->getMockBuilder(EmbridgeCatalog::class)->disableOriginalConstructor()->getMock(); $mock_catalog->expects($this->once())->method('getApplicationId')->willReturn($app_id); $mock_catalog_storage = $this->getMockBuilder(EntityStorageInterface::class)->disableOriginalConstructor()->getMock(); $mock_catalog_storage->expects($this->once())->method('load')->with($catalog_id)->willReturn($mock_catalog); $this->entityTypeManager->expects($this->exactly(2))->method('getStorage')->will($this->returnValueMap([['embridge_asset_entity', $mock_asset_storage], ['embridge_catalog', $mock_catalog_storage]])); $this->assetHelper->expects($this->once())->method('getAssetConversionUrl')->with($mock_asset, $app_id, 'thumb')->willReturn($source_url); $this->form->ajaxSave($form, $form_state); $expected_values = array_merge_recursive(['attributes' => ['src' => $source_url, 'data-entity-uuid' => self::MOCK_ASSET_UUID, 'data-entity-type' => 'embridge_asset_entity']], $intial_values); $actual_values = $form_state->getValues(); $this->assertEquals($expected_values, $actual_values); }
/** * Helper function. * * Display a link to bundle's view mode page if user has permission. * * @param string $entity_type * The type of the entity. * @param string $bundle * The bundle of the entity. * @param string $view_mode * A view mode. * * @return string * A link to the view mode of the bundle if user has access. * The view mode otherwise. */ public function displayViewModeLink($entity_type, $bundle, $view_mode = 'default') { $display = $view_mode; // Get entity type object from entity type name. $entity_type_object = $this->entityTypeManager->getDefinition($entity_type); // Prepare URL parameters. $parameters = array( 'view_mode_name' => $view_mode, ); $parameters += FieldUI::getRouteBundleParameter($entity_type_object, $bundle); // Route. if ($view_mode == 'default') { $route = "entity.entity_view_display.{$entity_type}.default"; } else { $route = "entity.entity_view_display.{$entity_type}.view_mode"; } $url = Url::fromRoute($route, $parameters); if ($url->renderAccess($url->toRenderArray())) { $display = Link::fromTextAndUrl($view_mode, $url); } return $display; }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $io = new DrupalStyle($input, $output); $viewId = $input->getArgument('view-id'); $view = $this->entityTypeManager->getStorage('view')->load($viewId); if (empty($view)) { $io->error(sprintf($this->trans('commands.views.debug.messages.not-found'), $viewId)); return; } try { $view->disable()->save(); $io->success(sprintf($this->trans('commands.views.disable.messages.disabled-successfully'), $view->get('label'))); } catch (\Exception $e) { $io->error($e->getMessage()); } }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { /** @var \Drupal\entity_clone\EntityClone\EntityCloneInterface $entity_clone_handler */ $entity_clone_handler = $this->entityTypeManager->getHandler($this->entityTypeDefinition->id(), 'entity_clone'); if ($this->entityTypeManager->hasHandler($this->entityTypeDefinition->id(), 'entity_clone_form')) { $entity_clone_form_handler = $this->entityTypeManager->getHandler($this->entityTypeDefinition->id(), 'entity_clone_form'); } $properties = []; if (isset($entity_clone_form_handler) && $entity_clone_form_handler) { $properties = $entity_clone_form_handler->getNewValues($form_state); } $cloned_entity = $entity_clone_handler->cloneEntity($this->entity, $this->entity->createDuplicate(), $properties); drupal_set_message($this->stringTranslationManager->translate('The entity <em>@entity (@entity_id)</em> of type <em>@type</em> was cloned', [ '@entity' => $this->entity->label(), '@entity_id' => $this->entity->id(), '@type' => $this->entity->getEntityTypeId(), ])); if ($cloned_entity && $cloned_entity->hasLinkTemplate('canonical')) { $form_state->setRedirect($cloned_entity->toUrl() ->getRouteName(), $cloned_entity->toUrl()->getRouteParameters()); } $form_state->setRedirect('<front>'); }
/** * @cover replacePlaceHolders */ public function testPlaceholdersAcrossReferences() { $user = $this->entityTypeManager->getStorage('user')->create(['name' => 'test', 'type' => 'user']); $this->node->uid->entity = $user; $text = 'test {{node.title}} and {{node.uid.entity.name}}'; $result = $this->placeholderResolver->replacePlaceHolders($text, ['node' => $this->node->getTypedData()]); $this->assertEquals('test test and test', $result); }
/** * Retrieves the uri of a bundle's graph from the settings. * * @param string $bundle_type_key * The bundle type key. E.g. 'node_type'. * @param string $bundle_id * The bundle machine name. * @param string $graph_name * The graph name. * * @return string * The graph uri. * * @throws \Exception * Thrown if the graph is not found. */ protected function getBundleGraphUriFromSettings($bundle_type_key, $bundle_id, $graph_name) { $bundle = $this->entityManager->getStorage($bundle_type_key)->load($bundle_id); $graph = $bundle->getThirdPartySetting('rdf_entity', 'graph_' . $graph_name, FALSE); if (!$graph) { throw new \Exception(format_string('Unable to determine graph %graph for bundle %bundle', ['%graph' => $graph_name, '%bundle' => $bundle->id()])); } return $graph; }
/** * {@inheritdoc} */ public function getDerivativeDefinitions($base_plugin_definition) { $this->derivatives = []; /** @var \Drupal\Core\Entity\EntityTypeInterface $entity_type */ foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) { $has_clone_path = $entity_type->hasLinkTemplate('clone-form'); $has_canonical_path = $entity_type->hasLinkTemplate('canonical'); if ($has_clone_path) { $this->derivatives["$entity_type_id.clone_tab"] = array( 'route_name' => "entity.$entity_type_id.clone_form", 'title' => $this->translationManager->translate('Clone'), 'base_route' => "entity.$entity_type_id." . ($has_canonical_path ? "canonical" : "edit_form"), 'weight' => 100, ); } } return $this->derivatives; }
private function queryBenzinarii($lat_ne, $lon_ne, $lat_sw, $lon_sw) { $data = new \stdClass(); $data->pins = []; $data->listing = ''; $query = $this->entity_query->get('node')->condition('field_coordonate.lat', (double) $lat_ne, '<')->condition('field_coordonate.lon', (double) $lon_ne, '<')->condition('field_coordonate.lat', (double) $lat_sw, '>')->condition('field_coordonate.lon', (double) $lon_sw, '>'); $ids = $query->execute(); if (!count($ids)) { return $data; } $entities = $this->entity_type_manager->getStorage('node')->loadMultiple($ids); foreach ($entities as $entity) { $pin = new \stdClass(); $pin->lat = $entity->field_coordonate->lat; $pin->lon = $entity->field_coordonate->lon; $pin->pret = PretCarburant::getPretCarburantCurent($entity); $pin->id = $entity->id(); if ($pin->pret) { $entity->pret = $pin->pret; $data->pins[$pin->id] = $pin; $render_entities[] = $entity; } } if (!count($render_entities)) { return $data; } uasort($render_entities, function ($a, $b) { if ($a->pret == $b->pret) { return 0; } else { if ($a->pret < $b->pret) { return -1; } else { return 1; } } }); $render = $this->entity_type_manager->getViewBuilder('node')->viewMultiple($render_entities, 'small_teaser'); $data->listing = '<div class="listing-benzinarii">' . $this->renderer->render($render) . '</div>'; return $data; }
/** * Get the directly previous revision. * * $entity->original will not ALWAYS be the previous revision. * * @param \Drupal\Core\Entity\ContentEntityInterface $entity * * @return \Drupal\Core\Entity\EntityInterface|null */ public function getPreviousRevision(ContentEntityInterface $entity) { $storage = $this->entityTypeManager->getStorage($entity->getEntityTypeId()); $query = $storage->getQuery(); $type = $entity->getEntityType(); $query->allRevisions()->condition($type->getKey('id'), $entity->id())->condition($type->getKey('revision'), $entity->getRevisionId(), '<')->sort($type->getKey('revision'), 'DESC')->pager(1); $revision_ids = $query->execute(); if ($revision_ids) { $revision_id = array_keys($revision_ids)[0]; return $storage->loadRevision($revision_id); } return NULL; }
/** * {@inheritdoc} */ public function validateFileSize(EmbridgeAssetEntityInterface $asset, $file_limit = 0, $user_limit = 0) { $user = $this->currentUser; $errors = array(); if ($file_limit && $asset->getSize() > $file_limit) { $errors[] = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size($asset->getSize()), '%maxsize' => format_size($file_limit))); } // Save a query by only calling spaceUsed() when a limit is provided. if ($user_limit && $this->entityTypeManager->getStorage('embridge_asset')->spaceUsed($user->id()) + $asset->getSize() > $user_limit) { $errors[] = t('The file is %filesize which would exceed your disk quota of %quota.', array('%filesize' => format_size($asset->getSize()), '%quota' => format_size($user_limit))); } return $errors; }
/** * Constructs a query object. * * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type * The entity type definition. * @param string $conjunction * - AND: all of the conditions on the query need to match. * - OR: at least one of the conditions on the query need to match. * @param \Drupal\rdf_entity\Database\Driver\sparql\Connection $connection * The database connection to run the query against. * @param array $namespaces * List of potential namespaces of the classes belonging to this query. * @param \Drupal\Core\Entity\EntityTypeManager $entity_type_manager * The entity type manager service object. * @param \Drupal\rdf_entity\RdfGraphHandler $rdf_graph_handler * The rdf graph handler service. * @param \Drupal\rdf_entity\RdfMappingHandler $rdf_mapping_handler * The rdf mapping handler service. * * @throws \Exception * Thrown when the storage passed is not an RdfEntitySparqlStorage. * * @todo: Is this exception check needed? */ public function __construct(EntityTypeInterface $entity_type, $conjunction, Connection $connection, array $namespaces, EntityTypeManager $entity_type_manager, RdfGraphHandler $rdf_graph_handler, RdfMappingHandler $rdf_mapping_handler) { parent::__construct($entity_type, $conjunction, $namespaces); $this->filter = new SparqlFilter(); $this->connection = $connection; $this->entityTypeManager = $entity_type_manager; $this->entityStorage = $this->entityTypeManager->getStorage($this->entityTypeId); $this->graphHandler = $rdf_graph_handler; $this->mappingHandler = $rdf_mapping_handler; if (!$this->entityStorage instanceof RdfEntitySparqlStorage) { throw new \Exception('Sparql storage is required for this query.'); } }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $io = new DrupalStyle($input, $output); $userId = $input->getOption('user-id'); if ($userId && $userId <= 1) { $io->error(sprintf($this->trans('commands.user.delete.errors.invalid-user-id'), $userId)); return 1; } if ($userId) { $user = $this->entityTypeManager->getStorage('user')->load($userId); if (!$user) { $io->error(sprintf($this->trans('commands.user.delete.errors.invalid-user'), $userId)); return 1; } try { $user->delete(); $io->info(sprintf($this->trans('commands.user.delete.messages.user-deleted'), $user->getUsername())); } catch (\Exception $e) { $io->error($e->getMessage()); return 1; } } $roles = $input->getOption('roles'); if ($roles) { $userStorage = $this->entityManager->getStorage('user'); $query = $this->entityQuery->get('user'); $query->condition('roles', is_array($roles) ? $roles : [$roles], 'IN'); $query->condition('uid', 1, '>'); $results = $query->execute(); $users = $userStorage->loadMultiple($results); $tableHeader = [$this->trans('commands.user.debug.messages.user-id'), $this->trans('commands.user.debug.messages.username')]; $tableRows = []; foreach ($users as $userId => $user) { try { $user->delete(); $tableRows['success'][] = [$userId, $user->getUsername()]; } catch (\Exception $e) { $tableRows['error'][] = [$userId, $user->getUsername()]; $io->error($e->getMessage()); return 1; } } if ($tableRows['success']) { $io->table($tableHeader, $tableRows['success']); $io->success(sprintf($this->trans('commands.user.delete.messages.users-deleted'), count($tableRows['success']))); } } }
/** * @param \Drupal\Console\Style\DrupalStyle $io * @param $tag * @param $status */ protected function viewList(DrupalStyle $io, $tag, $status) { $views = $this->entityTypeManager->getStorage('view')->loadMultiple(); $tableHeader = [$this->trans('commands.views.debug.messages.view-id'), $this->trans('commands.views.debug.messages.view-name'), $this->trans('commands.views.debug.messages.tag'), $this->trans('commands.views.debug.messages.status'), $this->trans('commands.views.debug.messages.path')]; $tableRows = []; foreach ($views as $view) { if ($status != -1 && $view->status() != $status) { continue; } if (isset($tag) && $view->get('tag') != $tag) { continue; } $tableRows[] = [$view->get('id'), $view->get('label'), $view->get('tag'), $view->status() ? $this->trans('commands.common.status.enabled') : $this->trans('commands.common.status.disabled'), $this->viewDisplayPaths($view)]; } $io->table($tableHeader, $tableRows, 'compact'); }
protected function getViewDisplays($contentType, $optional = false) { $view_display_definition = $this->entityTypeManager->getDefinition('entity_view_display'); $view_display_storage = $this->entityTypeManager->getStorage('entity_view_display'); foreach ($view_display_storage->loadMultiple() as $view_display) { $view_display_name = $view_display_definition->getConfigPrefix() . '.' . $view_display->id(); $view_display_name_config = $this->getConfiguration($view_display_name); // Only select fields related with content type if ($view_display_name_config['bundle'] == $contentType) { $this->configExport[$view_display_name] = array('data' => $view_display_name_config, 'optional' => $optional); // Include dependencies in export files if ($dependencies = $this->fetchDependencies($view_display_name_config, 'config')) { $this->resolveDependencies($dependencies, $optional); } } } }
/** * @cover fetchDataByPropertyPath */ public function testBubbleableMetadata() { $this->node->field_integer->setValue([]); // Save the node, so that it gets an ID and it has a cache tag. $this->node->save(); // Also add a user for testing cache tags of references. $user = $this->entityTypeManager->getStorage('user')->create(['name' => 'test', 'type' => 'user']); $user->save(); $this->node->uid->entity = $user; $bubbleable_metadata = new BubbleableMetadata(); $this->dataFetcher->fetchDataByPropertyPath($this->node->getTypedData(), 'title.value', $bubbleable_metadata)->getValue(); $expected = ['node:' . $this->node->id()]; $this->assertEquals($expected, $bubbleable_metadata->getCacheTags()); // Test cache tags of references are added correctly. $this->dataFetcher->fetchDataByPropertyPath($this->node->getTypedData(), 'uid.entity.name', $bubbleable_metadata)->getValue(); $expected = ['node:' . $this->node->id(), 'user:' . $user->id()]; $this->assertEquals($expected, $bubbleable_metadata->getCacheTags()); }
protected function execute(InputInterface $input, OutputInterface $output) { $io = new DrupalStyle($input, $output); $module = $input->getOption('module'); $viewId = $input->getArgument('view-id'); $optionalConfig = $input->getOption('optional-config'); $includeModuleDependencies = $input->getOption('include-module-dependencies'); $viewTypeDefinition = $this->entityTypeManager->getDefinition('view'); $viewTypeName = $viewTypeDefinition->getConfigPrefix() . '.' . $viewId; $viewNameConfig = $this->getConfiguration($viewTypeName); $this->configExport[$viewTypeName] = array('data' => $viewNameConfig, 'optional' => $optionalConfig); // Include config dependencies in export files if ($dependencies = $this->fetchDependencies($viewNameConfig, 'config')) { $this->resolveDependencies($dependencies, $optionalConfig); } // Include module dependencies in export files if export is not optional if ($includeModuleDependencies) { if ($dependencies = $this->fetchDependencies($viewNameConfig, 'module')) { $this->exportModuleDependencies($io, $module, $dependencies); } } $this->exportConfigToModule($module, $io, $this->trans('commands.views.export.messages.view_exported')); }
/** * Returns a list of mapped properties for the passed content entity. * * @param \Drupal\Core\Entity\EntityInterface $entity * A content entity. * * @return array * An array of mappings between predicates and field properties. All * fields, and properties of the entity and the fields, that are available * will be returned. */ public function getEntityTypeMappedProperties(EntityInterface $entity) { $bundle = $entity->bundle(); $properties = []; // Collect impacted fields. $definitions = $this->entityManager->getFieldDefinitions($entity->getEntityTypeId(), $bundle); $base_field_definitions = $this->entityManager->getBaseFieldDefinitions($entity->getEntityTypeId()); $rdf_bundle_entity = $this->entityManager->getStorage($entity->getEntityType()->getBundleEntityType())->load($bundle); /** @var \Drupal\Core\Field\BaseFieldDefinition $field_definition */ foreach ($definitions as $field_name => $field_definition) { /** @var \Drupal\field\Entity\FieldStorageConfig $storage_definition */ $storage_definition = $field_definition->getFieldStorageDefinition(); if (!$storage_definition instanceof FieldStorageConfig) { continue; } foreach ($storage_definition->getColumns() as $column => $column_info) { if ($property = $storage_definition->getThirdPartySetting('rdf_entity', 'mapping_' . $column, FALSE)) { $properties['by_field'][$field_name][$column] = $property; $properties['flat'][$property] = $property; } } } foreach ($base_field_definitions as $field_name => $base_field_definition) { $field_data = $rdf_bundle_entity->getThirdPartySetting('rdf_entity', 'mapping_' . $field_name, FALSE); if (!$field_data) { continue; } foreach ($field_data as $column => $predicate) { if (empty($predicate)) { continue; } $properties['by_field'][$field_name][$column] = $predicate; $properties['flat'][$predicate] = $predicate; } } return $properties; }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state, $field_key = '') { // Initialize field. $field = array(); // Fetch field if it already exists. if (!empty($field_key)) { $field = $this->config('ds.field.' . $field_key)->get(); } // Save the field for future reuse. $this->field = $field; $form['name'] = array('#title' => t('Label'), '#type' => 'textfield', '#default_value' => isset($field['label']) ? $field['label'] : '', '#description' => t('The human-readable label of the field.'), '#maxlength' => 128, '#required' => TRUE, '#size' => 30); $form['id'] = array('#type' => 'machine_name', '#default_value' => isset($field['id']) ? $field['id'] : '', '#maxlength' => 32, '#description' => t('The machine-readable name of this field. This name must contain only lowercase letters and underscores. This name must be unique.'), '#disabled' => !empty($field['id']), '#machine_name' => array('exists' => array($this, 'uniqueFieldName'), 'source' => array('name'))); $entity_options = array(); $entities = $this->entityTypeManager->getDefinitions(); foreach ($entities as $entity_type => $entity_info) { if ($entity_info->get('field_ui_base_route') || $entity_type == 'ds_views') { $entity_options[$entity_type] = Unicode::ucfirst(str_replace('_', ' ', $entity_type)); } } $form['entities'] = array('#title' => t('Entities'), '#description' => t('Select the entities for which this field will be made available.'), '#type' => 'checkboxes', '#required' => TRUE, '#options' => $entity_options, '#default_value' => isset($field['entities']) ? $field['entities'] : array()); $form['ui_limit'] = array('#title' => t('Limit field'), '#description' => t('Limit this field on field UI per bundles and/or view modes. The values are in the form of $bundle|$view_mode, where $view_mode may be either a view mode set to use custom settings, or \'default\'. You may use * to select all, e.g article|*, *|full or *|*. Enter one value per line.'), '#type' => 'textarea', '#default_value' => isset($field['ui_limit']) ? $field['ui_limit'] : ''); $form['submit'] = array('#type' => 'submit', '#value' => t('Save'), '#weight' => 100); return $form; }
/** * {@inheritdoc} */ protected function interact(InputInterface $input, OutputInterface $output) { $io = new DrupalStyle($input, $output); $config_types = $this->getConfigTypes(); $config_name = $input->getArgument('config-name'); if (!$config_name) { $config_type = $io->choiceNoList($this->trans('commands.config.export.single.questions.config-type'), array_keys($config_types), $this->trans('commands.config.export.single.options.simple-configuration')); $config_names = $this->getConfigNames($config_type); $config_name = $io->choiceNoList($this->trans('commands.config.export.single.questions.config-name'), array_keys($config_names)); if ($config_type !== 'system.simple') { $definition = $this->entityTypeManager->getDefinition($config_type); $config_name = $definition->getConfigPrefix() . '.' . $config_name; } $input->setArgument('config-name', $config_name); } $module = $input->getOption('module'); if ($module) { $optionalConfig = $input->getOption('optional-config'); if (!$optionalConfig) { $optionalConfig = $io->confirm($this->trans('commands.config.export.single.questions.optional-config'), true); $input->setOption('optional-config', $optionalConfig); } } }
/** * Constructs a FacetForm object. * * @param \Drupal\Core\Entity\EntityTypeManager $entity_type_manager * The entity manager. * @param \Drupal\facets\FacetSource\FacetSourcePluginManager $facet_source_plugin_manager * The plugin manager for facet sources. * @param \Drupal\facets\Processor\ProcessorPluginManager $processor_plugin_manager * The plugin manager for processors. */ public function __construct(EntityTypeManager $entity_type_manager, FacetSourcePluginManager $facet_source_plugin_manager, ProcessorPluginManager $processor_plugin_manager) { $this->facetStorage = $entity_type_manager->getStorage('facets_facet'); $this->facetSourcePluginManager = $facet_source_plugin_manager; $this->processorPluginManager = $processor_plugin_manager; }