/** * Tests ConfigurableEventHandlerEntityBundle. * * Test that rules are triggered correctly based upon the fully qualified * event name as well as the base event name. * * @todo Add integrity check that node.field_integer is detected by Rules. */ public function testConfigurableEventHandler() { // Create rule1 with the 'rules_entity_presave:node--page' event. $rule1 = $this->expressionManager->createRule(); $rule1->addAction('rules_test_log', ContextConfig::create()->map('message', 'node.field_integer.0.value')); $config_entity1 = $this->storage->create(['id' => 'test_rule1']); $config_entity1->set('events', [['event_name' => 'rules_entity_presave:node--page']]); $config_entity1->set('expression', $rule1->getConfiguration()); $config_entity1->save(); // Create rule2 with the 'rules_entity_presave:node' event. $rule2 = $this->expressionManager->createRule(); $rule2->addAction('rules_test_log', ContextConfig::create()->map('message', 'node.field_integer.1.value')); $config_entity2 = $this->storage->create(['id' => 'test_rule2']); $config_entity2->set('events', [['event_name' => 'rules_entity_presave:node']]); $config_entity2->set('expression', $rule2->getConfiguration()); $config_entity2->save(); // The logger instance has changed, refresh it. $this->logger = $this->container->get('logger.channel.rules'); // Add node.field_integer.0.value to rules log message, read result. $this->node->field_integer->setValue(['0' => 11, '1' => 22]); // Trigger node save. $entity_type_id = $this->node->getEntityTypeId(); $event = new EntityEvent($this->node, [$entity_type_id => $this->node]); $event_dispatcher = \Drupal::service('event_dispatcher'); $event_dispatcher->dispatch("rules_entity_presave:{$entity_type_id}", $event); // Test that the action in the rule1 logged node value. $this->assertRulesLogEntryExists(11, 1); // Test that the action in the rule2 logged node value. $this->assertRulesLogEntryExists(22, 0); }
/** * {@inheritdoc} */ public function view(EntityInterface $entity, $view_mode = 'full', $langcode = NULL) { $message = $this->contactMessageStorage->create(['contact_form' => $entity->id()]); $form = $this->entityFormBuilder->getForm($message); $form['#title'] = $entity->label(); $form['#cache']['contexts'][] = 'user.permissions'; $this->renderer->addCacheableDependency($form, $this->config); return $form; }
/** * Presents the custom block creation form. * * @param \Drupal\block_content\BlockContentTypeInterface $block_content_type * The custom block type to add. * @param \Symfony\Component\HttpFoundation\Request $request * The current request object. * * @return array * A form array as expected by drupal_render(). */ public function addForm(BlockContentTypeInterface $block_content_type, Request $request) { $block = $this->blockContentStorage->create(array('type' => $block_content_type->id())); if (($theme = $request->query->get('theme')) && in_array($theme, array_keys(list_themes()))) { // We have navigated to this page from the block library and will keep track // of the theme for redirecting the user to the configuration page for the // newly created block in the given theme. $block->setTheme($theme); } return $this->entityFormBuilder()->getForm($block); }
/** * Make sure that expressions using context definitions can be exported. */ public function testContextDefinitionExport() { $rule = $this->expressionManager->createRule(['context_definitions' => ['test' => ContextDefinition::create('string')->setLabel('Test string')->toArray()]]); $config_entity = $this->storage->create(['id' => 'test_rule'])->setExpression($rule); $config_entity->save(); $loaded_entity = $this->storage->load('test_rule'); // Create the Rules expression object from the configuration. $expression = $loaded_entity->getExpression(); $context_definitions = $expression->getContextDefinitions(); $this->assertEqual($context_definitions['test']->getDataType(), 'string', 'Data type of context definition is correct.'); $this->assertEqual($context_definitions['test']->getLabel(), 'Test string', 'Label of context definition is correct.'); }
/** * Make sure that expressions using context definitions can be exported. */ public function testContextDefinitionExport() { $component = RulesComponent::create($this->expressionManager->createRule())->addContextDefinition('test', ContextDefinition::create('string')->setLabel('Test string')); $config_entity = $this->storage->create(['id' => 'test_rule'])->updateFromComponent($component); $config_entity->save(); $loaded_entity = $this->storage->load('test_rule'); // Create the Rules expression object from the configuration. $expression = $loaded_entity->getExpression(); $this->assertInstanceOf(Rule::class, $expression); $context_definitions = $loaded_entity->getContextDefinitions(); $this->assertEquals($context_definitions['test']->getDataType(), 'string', 'Data type of context definition is correct.'); $this->assertEquals($context_definitions['test']->getLabel(), 'Test string', 'Label of context definition is correct.'); }
/** * {@inheritdoc} */ public function import($currencyCode) { if ($existingEntity = $this->storage->load($currencyCode)) { // Pretend the currency was just imported. return $existingEntity; } $defaultLangcode = $this->languageManager->getDefaultLanguage()->getId(); $currency = $this->externalRepository->get($currencyCode, $defaultLangcode, 'en'); $values = [ 'langcode' => $defaultLangcode, 'currencyCode' => $currency->getCurrencyCode(), 'name' => $currency->getName(), 'numericCode' => $currency->getNumericCode(), 'symbol' => $currency->getSymbol(), 'fractionDigits' => $currency->getFractionDigits(), ]; $entity = $this->storage->create($values); $entity->trustData()->save(); if ($this->languageManager->isMultilingual()) { // Import translations for any additional languages the site has. $languages = $this->languageManager->getLanguages(LanguageInterface::STATE_CONFIGURABLE); $languages = array_diff_key($languages, [$defaultLangcode => $defaultLangcode]); $langcodes = array_map(function ($language) { return $language->getId(); }, $languages); $this->importEntityTranslations($entity, $langcodes); } return $entity; }
/** * {@inheritdoc} */ public function view(EntityInterface $entity, $view_mode = 'full', $langcode = NULL) { if ($entity->status()) { $message = $this->contactMessageStorage->create([ 'contact_form' => $entity->id(), ]); $form = $this->entityFormBuilder->getForm($message); $form['#title'] = $entity->label(); $form['#cache']['contexts'][] = 'user.permissions'; $this->renderer->addCacheableDependency($form, $this->config); } else { // Form disabled, display a custom message using a template. $form['disabled_form_error'] = array( '#theme' => 'contact_storage_disabled_form', '#contact_form' => $entity, '#redirect_uri' => $entity->getThirdPartySetting('contact_storage', 'redirect_uri', ''), '#disabled_form_message' => $entity->getThirdPartySetting('contact_storage', 'disabled_form_message', t('This contact form has been disabled.')), ); } // Add required cacheability metadata from the contact form entity, so that // changing it invalidates the cache. $this->renderer->addCacheableDependency($form, $entity); return $form; }
/** * Creates and gets test image file. * * @return \Drupal\file\FileInterface * File object. */ protected function getTestFile() { file_unmanaged_copy(drupal_get_path('module', 'crop') . '/tests/files/sarajevo.png', PublicStream::basePath()); return $this->fileStorage->create([ 'uri' => 'public://sarajevo.png', 'status' => FILE_STATUS_PERMANENT, ]); }
/** * {@inheritdoc} */ public function loadMultiple(EntityStorageInterface $storage, array $sub_ids = NULL) { if (isset($this->configuration['bundle_migration'])) { /** @var \Drupal\migrate\Entity\MigrationInterface $bundle_migration */ $bundle_migration = $storage->load($this->configuration['bundle_migration']); $source_id = array_keys($bundle_migration->getSourcePlugin()->getIds())[0]; $this->bundles = array(); foreach ($bundle_migration->getSourcePlugin()->getIterator() as $row) { $this->bundles[] = $row[$source_id]; } } else { // This entity type has no bundles ('user', 'feed', etc). $this->bundles = array($this->migration->getSourcePlugin()->entityTypeId()); } $sub_ids_to_load = isset($sub_ids) ? array_intersect($this->bundles, $sub_ids) : $this->bundles; $migrations = array(); foreach ($sub_ids_to_load as $id) { $values = $this->migration->toArray(); $values['id'] = $this->migration->id() . ':' . $id; $values['source']['bundle'] = $id; /** @var \Drupal\migrate_drupal\Entity\MigrationInterface $migration */ $migration = $storage->create($values); if ($migration->getSourcePlugin()->checkRequirements()) { $fields = array_keys($migration->getSourcePlugin()->fields()); $migration->process += array_combine($fields, $fields); $migrations[$migration->id()] = $migration; } } return $migrations; }
/** * {@inheritdoc} */ public function createCart($orderType, StoreInterface $store, AccountInterface $account = NULL) { $account = $account ?: $this->currentUser; $uid = $account->id(); $storeId = $store->id(); if ($this->getCartId($orderType, $store, $account)) { // Don't allow multiple cart orders matching the same criteria. throw new DuplicateCartException("A cart order for type '$orderType', store '$storeId' and account '$uid' already exists."); } // Create the new cart order. $cart = $this->orderStorage->create([ 'type' => $orderType, 'store_id' => $storeId, 'uid' => $uid, 'cart' => TRUE, ]); $cart->save(); // Store the new cart order id in the anonymous user's session so that it // can be retrieved on the next page load. if ($account->isAnonymous()) { $this->cartSession->addCartId($cart->id()); } // Cart data has already been loaded, add the new cart order to the list. if (isset($this->cartData[$uid])) { $this->cartData[$uid][$cart->id()] = [ 'type' => $orderType, 'store_id' => $storeId, ]; } return $cart; }
/** * {@inheritdoc} */ public function loadMultiple(EntityStorageInterface $storage, array $sub_ids = NULL) { /** @var \Drupal\migrate\Entity\MigrationInterface $bundle_migration */ $bundle_migration = $storage->load('d6_taxonomy_vocabulary'); $migrate_executable = new MigrateExecutable($bundle_migration, new MigrateMessage()); $process = array_intersect_key($bundle_migration->get('process'), $bundle_migration->getDestinationPlugin()->getIds()); $migrations = array(); $vid_map = array(); foreach ($bundle_migration->getIdMap() as $key => $value) { $old_vid = unserialize($key)['sourceid1']; $new_vid = $value['destid1']; $vid_map[$old_vid] = $new_vid; } foreach ($bundle_migration->getSourcePlugin()->getIterator() as $source_row) { $row = new Row($source_row, $source_row); $migrate_executable->processRow($row, $process); $old_vid = $source_row['vid']; $new_vid = $row->getDestinationProperty('vid'); $vid_map[$old_vid] = $new_vid; } foreach ($vid_map as $old_vid => $new_vid) { $values = $this->migration->toArray(); $migration_id = $this->migration->id() . ':' . $old_vid; $values['id'] = $migration_id; $values['source']['vid'] = $old_vid; $values['process'][$new_vid] = 'tid'; $migrations[$migration_id] = $storage->create($values); } return $migrations; }
/** * {@inheritdoc} */ protected function generateElements(array $values) { $num = $values['num']; $kill = $values['kill']; $pass = $values['pass']; $age = $values['time_range']; $roles = array_filter($values['roles']); if ($kill) { $uids = $this->userStorage->getQuery()->condition('uid', 1, '>')->execute(); $users = $this->userStorage->loadMultiple($uids); $this->userStorage->delete($users); $this->setMessage($this->formatPlural(count($uids), '1 user deleted', '@count users deleted.')); } if ($num > 0) { $names = array(); while (count($names) < $num) { $name = $this->getRandom()->word(mt_rand(6, 12)); $names[$name] = ''; } if (empty($roles)) { $roles = array(DRUPAL_AUTHENTICATED_RID); } foreach ($names as $name => $value) { $account = $this->userStorage->create(array('uid' => NULL, 'name' => $name, 'pass' => $pass, 'mail' => $name . '@example.com', 'status' => 1, 'created' => REQUEST_TIME - mt_rand(0, $age), 'roles' => array_values($roles), 'devel_generate' => TRUE)); // Populate all fields with sample values. $this->populateFields($account); $account->save(); } } $this->setMessage($this->t('@num_users created.', array('@num_users' => $this->formatPlural($num, '1 user', '@count users')))); }
/** * Imports a single tax rate amount. * * @param \CommerceGuys\Tax\Model\TaxRateAmountInterface $taxRateAmount * The tax rate amount to import. */ protected function importTaxRateAmount(ExternalTaxRateAmountInterface $taxRateAmount) { $startDate = $taxRateAmount->getStartDate() ? $taxRateAmount->getStartDate()->getTimestamp() : NULL; $endDate = $taxRateAmount->getEndDate() ? $taxRateAmount->getEndDate()->getTimestamp() : NULL; $values = ['rate' => $taxRateAmount->getRate()->getId(), 'id' => $taxRateAmount->getId(), 'amount' => $taxRateAmount->getAmount(), 'startDate' => $startDate, 'endDate' => $endDate]; return $this->taxRateAmountStorage->create($values); }
/** * Test that the user logout hook triggers the Rules event listener. */ public function testUserLogoutEvent() { $rule = $this->expressionManager->createInstance('rules_reaction_rule', ['event' => 'rules_user_logout']); $rule->addCondition('rules_test_true'); $rule->addAction('rules_test_log'); $config_entity = $this->storage->create(['id' => 'test_rule', 'expression_id' => 'rules_reaction_rule', 'event' => 'rules_user_logout', 'configuration' => $rule->getConfiguration()]); $config_entity->save(); // Rebuild the container so that the newly configured event gets picked up. $this->container->get('kernel')->rebuildContainer(); // The logger instance has changed, refresh it. $this->logger = $this->container->get('logger.channel.rules'); $account = $this->container->get('current_user'); // Invoke the hook manually which should trigger the rule. rules_user_logout($account); // Test that the action in the rule logged something. $this->assertRulesLogEntryExists('action called'); }
/** * {@inheritdoc} */ protected function newEntity(FeedInterface $feed) { $values = $this->configuration['values']; $entity = $this->storageController->create($values); $entity->enforceIsNew(); if ($entity instanceof EntityOwnerInterface) { $entity->setOwnerId($this->configuration['owner_id']); } return $entity; }
/** * {@inheritdoc} */ public function postSave(EntityStorageInterface $storage, $update = TRUE) { // Used to test secondary writes during config sync. if ($this->id() == 'primary') { $secondary = $storage->create(array('id' => 'secondary', 'label' => 'Secondary Default')); $secondary->save(); } if ($this->id() == 'deleter') { $deletee = $storage->load('deletee'); $deletee->delete(); } }
public function createTestEntity(EntityStorageInterface $storage, array $values) { switch ($storage->getEntityTypeId()) { case 'block_content': $values['info'] = $this->randomMachineName(); break; case 'user': $values['name'] = $this->randomMachineName(); break; } return $storage->create($values); }
/** * Create one product variation. */ protected function generateProductVariation(&$results) { $product_variation_type = 'default'; // Need to be generated. $max = isset($results['title_var_length']) ? $results['title_var_length'] : $results['title_length']; $product_variation_title = $this->getRandom()->word(mt_rand(1, $max)); $min = isset($results['price_min']) ? $results['price_min'] : $this->getSetting('price_min'); $max = isset($results['price_max']) ? $results['price_max'] : $this->getSetting('price_max'); $product_variation = $this->variationStorage->create(array('variation_id' => NULL, 'type' => $product_variation_type, 'langcode' => $this->getLangcode($results), 'sku' => $product_variation_title, 'price' => array('amount' => mt_rand($min, $max), 'currency_code' => $results['currency']), 'devel_generate' => TRUE)); $this->populateFields($product_variation); $product_variation->save(); return $product_variation; }
/** * {@inheritdoc} */ public function loadMultiple(EntityStorageInterface $storage, array $sub_ids = NULL) { if (isset($this->configuration['bundle_migration'])) { /** @var \Drupal\migrate\Entity\MigrationInterface $bundle_migration */ $bundle_migration = $storage->load($this->configuration['bundle_migration']); $source_id = array_keys($bundle_migration->getSourcePlugin()->getIds())[0]; $this->bundles = array(); foreach ($bundle_migration->getSourcePlugin()->getIterator() as $row) { $this->bundles[] = $row[$source_id]; } } else { // This entity type has no bundles ('user', 'feed', etc). $this->bundles = array($this->migration->getSourcePlugin()->entityTypeId()); } $sub_ids_to_load = isset($sub_ids) ? array_intersect($this->bundles, $sub_ids) : $this->bundles; $migrations = array(); foreach ($sub_ids_to_load as $id) { $values = $this->migration->toArray(); $values['id'] = $this->migration->id() . ':' . $id; $values['source']['bundle'] = $id; /** @var \Drupal\migrate_drupal\Entity\MigrationInterface $migration */ $migration = $storage->create($values); try { $migration->getSourcePlugin()->checkRequirements(); $source_plugin = $migration->getSourcePlugin(); if ($source_plugin instanceof CckFieldMigrateSourceInterface) { foreach ($source_plugin->fieldData() as $field_name => $data) { switch ($data['type']) { case 'link': $this->processLinkField($field_name, $data, $migration); break; case 'filefield': $this->processFileField($field_name, $data, $migration); break; case 'text': $this->processTextField($field_name, $data, $migration); break; default: $migration->setProcessOfProperty($field_name, $field_name); } } } else { $fields = array_keys($migration->getSourcePlugin()->fields()); $migration->setProcess($migration->getProcess() + array_combine($fields, $fields)); } $migrations[$migration->id()] = $migration; } catch (RequirementsException $e) { } } return $migrations; }
/** * Generates taxonomy terms for a list of given vocabularies. * * @param int $records * Number of terms to create in total. * @param \Drupal\taxonomy\TermInterface[] $vocabs * List of vocabularies to populate. * @param int $maxlength * (optional) Maximum length per term. * * @return array * The list of names of the created terms. */ protected function generateTerms($records, $vocabs, $maxlength = 12) { $terms = array(); // Insert new data: $max = db_query('SELECT MAX(tid) FROM {taxonomy_term_data}')->fetchField(); $start = time(); for ($i = 1; $i <= $records; $i++) { $name = $this->getRandom()->word(mt_rand(2, $maxlength)); $values = array('name' => $name, 'description' => 'description of ' . $name, 'format' => filter_fallback_format(), 'weight' => mt_rand(0, 10), 'langcode' => Language::LANGCODE_NOT_SPECIFIED); switch ($i % 2) { case 1: $vocab = $vocabs[array_rand($vocabs)]; $values['vid'] = $vocab->id(); $values['parent'] = array(0); break; default: while (TRUE) { // Keep trying to find a random parent. $candidate = mt_rand(1, $max); $query = db_select('taxonomy_term_data', 't'); $parent = $query->fields('t', array('tid', 'vid'))->condition('t.vid', array_keys($vocabs), 'IN')->condition('t.tid', $candidate, '>=')->range(0, 1)->execute()->fetchAssoc(); if ($parent['tid']) { break; } } $values['parent'] = array($parent['tid']); // Slight speedup due to this property being set. $values['vid'] = $parent['vid']; break; } $term = $this->termStorage->create($values); // Populate all fields with sample values. $this->populateFields($term); $term->save(); $max++; if (function_exists('drush_log')) { $feedback = drush_get_option('feedback', 1000); if ($i % $feedback == 0) { $now = time(); drush_log(dt('Completed @feedback terms (@rate terms/min)', array('@feedback' => $feedback, '@rate' => $feedback * 60 / ($now - $start))), 'ok'); $start = $now; } } // Limit memory usage. Only report first 20 created terms. if ($i < 20) { $terms[] = $term->label(); } unset($term); } return $terms; }
/** * Subscribes to a feed. */ public function onPostFetch(FetchEvent $event) { $feed = $event->getFeed(); $fetcher = $feed->getType()->getFetcher(); $subscription = $this->storage->load($feed->id()); if (!$fetcher->getConfiguration('use_pubsubhubbub')) { return $this->unsubscribe($feed, $subscription); } if (!($hub = $this->findRelation($event->getFetcherResult(), 'hub'))) { $hub = $fetcher->getConfiguration('fallback_hub'); } // No hub found. if (!$hub) { return $this->unsubscribe($feed, $subscription); } // Used to make other URLs absolute. $source_url = Url::fromString($feed->getSource()); $hub = (string) $source_url->combine($hub); // If there is a rel="self" relation. if ($topic = $this->findRelation($event->getFetcherResult(), 'self')) { $topic = (string) $source_url->combine($topic); $feed->setSource($topic); } else { $topic = $feed->getSource(); } // Subscription does not exist yet. if (!$subscription) { $subscription = $this->storage->create(['fid' => $feed->id(), 'topic' => $topic, 'hub' => $hub]); return $this->subscribe($feed, $subscription); } if ($topic !== $subscription->getTopic() || $subscription->getHub() !== $hub || $subscription->getState() !== 'subscribed') { // Unsubscribe from the old feed. $this->unsubscribe($feed, $subscription); $subscription = $this->storage->create(['fid' => $feed->id(), 'topic' => $topic, 'hub' => $hub]); return $this->subscribe($feed, $subscription); } }
/** * Tests deleting a payment status. */ protected function testDelete() { $payment_status_id = strtolower($this->randomMachineName()); /** @var \Drupal\payment\Entity\PaymentStatusInterface $status */ $status = $this->paymentStatusStorage->create([]); $status->setId($payment_status_id)->save(); $path = 'admin/config/services/payment/status/delete/' . $payment_status_id; $this->drupalGet($path); $this->assertResponse(403); $this->drupalLogin($this->drupalCreateUser(array('payment.payment_status.administer'))); $this->drupalGet($path); $this->assertResponse(200); $this->drupalPostForm(NULL, [], t('Delete')); $this->assertNull($this->paymentStatusStorage->loadUnchanged($payment_status_id)); }
/** * Generates vocabularies. * * @param int $records * Number of vocabularies to create. * @param int $maxlength * (optional) Maximum length for vocabulary name. * * @return array * Array containing the generated vocabularies id. */ protected function generateVocabularies($records, $maxlength = 12) { $vocabularies = array(); // Insert new data: for ($i = 1; $i <= $records; $i++) { $name = $this->getRandom()->word(mt_rand(2, $maxlength)); $vocabulary = $this->vocabularyStorage->create(array('name' => $name, 'vid' => Unicode::strtolower($name), 'langcode' => Language::LANGCODE_NOT_SPECIFIED, 'description' => "Description of {$name}", 'hierarchy' => 1, 'weight' => mt_rand(0, 10), 'multiple' => 1, 'required' => 0, 'relations' => 1)); // Populate all fields with sample values. $this->populateFields($vocabulary); $vocabulary->save(); $vocabularies[] = $vocabulary->id(); unset($vocabulary); } return $vocabularies; }
/** * Creates or loads an entity. * * @param \Drupal\migrate\Row $row * The row object. * @param array $old_destination_id_values * The old destination ids. * * @return \Drupal\Core\Entity\EntityInterface * The entity we're importing into. */ protected function getEntity(Row $row, array $old_destination_id_values) { $entity_id = $old_destination_id_values ? reset($old_destination_id_values) : $this->getEntityId($row); if (!empty($entity_id) && ($entity = $this->storage->load($entity_id))) { $this->updateEntity($entity, $row); } else { // Stubs might need some required fields filled in. if ($row->isStub()) { $this->processStubRow($row); } $entity = $this->storage->create($row->getDestination()); $entity->enforceIsNew(); } return $entity; }
/** * Creates or loads an entity. * * @param \Drupal\migrate\Row $row * The row object. * @param array $old_destination_id_values * The old destination ids. * * @return \Drupal\Core\Entity\EntityInterface * The entity we're importing into. */ protected function getEntity(Row $row, array $old_destination_id_values) { $entity_id = $old_destination_id_values ? reset($old_destination_id_values) : $this->getEntityId($row); if (!empty($entity_id) && ($entity = $this->storage->load($entity_id))) { $this->updateEntity($entity, $row); } else { $values = $row->getDestination(); // Stubs might not have the bundle specified. if ($row->isStub()) { $values = $this->processStubValues($values); } $entity = $this->storage->create($values); $entity->enforceIsNew(); } return $entity; }
/** * Enables the REST service interface for a specific entity type. * * @param string|false $resource_type * The resource type that should get REST API enabled or FALSE to disable all * resource types. * @param string $method * The HTTP method to enable, e.g. GET, POST etc. * @param string|array $format * (Optional) The serialization format, e.g. hal_json, or a list of formats. * @param array $auth * (Optional) The list of valid authentication methods. */ protected function enableService($resource_type, $method = 'GET', $format = NULL, array $auth = []) { if ($resource_type) { // Enable REST API for this entity type. $resource_config_id = str_replace(':', '.', $resource_type); // get entity by id /** @var \Drupal\rest\RestResourceConfigInterface $resource_config */ $resource_config = $this->resourceConfigStorage->load($resource_config_id); if (!$resource_config) { $resource_config = $this->resourceConfigStorage->create([ 'id' => $resource_config_id, 'granularity' => RestResourceConfigInterface::METHOD_GRANULARITY, 'configuration' => [] ]); } $configuration = $resource_config->get('configuration'); if (is_array($format)) { for ($i = 0; $i < count($format); $i++) { $configuration[$method]['supported_formats'][] = $format[$i]; } } else { if ($format == NULL) { $format = $this->defaultFormat; } $configuration[$method]['supported_formats'][] = $format; } if (!is_array($auth) || empty($auth)) { $auth = $this->defaultAuth; } foreach ($auth as $auth_provider) { $configuration[$method]['supported_auth'][] = $auth_provider; } $resource_config->set('configuration', $configuration); $resource_config->save(); } else { foreach ($this->resourceConfigStorage->loadMultiple() as $resource_config) { $resource_config->delete(); } } $this->rebuildCache(); }
/** * Creates a currency entity from a currency from the repository. * * @param string $currency_code * * @return \Drupal\currency\Entity\CurrencyInterface * * @throws \InvalidArgumentException * Thrown when no currency with the given currency code exists. */ protected function createCurrencyFromRepository($currency_code) { /** @var \Drupal\currency\Entity\CurrencyInterface $currency_entity */ $currency_entity = $this->currencyStorage->create(); $currency_resource = $this->currencyResourceRepository->loadCurrency($currency_code); if (is_null($currency_resource)) { throw new \InvalidArgumentException(sprintf('No currency with currency code %s exists.', $currency_code)); } $currency_entity->setCurrencyCode($currency_resource->getCurrencyCode()); $currency_entity->setCurrencyNumber($currency_resource->getCurrencyNumber()); $currency_entity->setLabel($currency_resource->getLabel()); $currency_entity->setSign($currency_resource->getSign()); $currency_entity->setAlternativeSigns($currency_resource->getAlternativeSigns()); $currency_entity->setSubunits($currency_resource->getSubunits()); $currency_entity->setRoundingStep($currency_resource->getRoundingStep()); $currency_entity->setUsages($currency_resource->getUsages()); return $currency_entity; }
/** * Create one node. Used by both batch and non-batch code branches. */ protected function develGenerateContentAddNode(&$results) { if (!isset($results['time_range'])) { $results['time_range'] = 0; } $users = $results['users']; $node_type = array_rand(array_filter($results['node_types'])); $uid = $users[array_rand($users)]; $node = $this->nodeStorage->create(array('nid' => NULL, 'type' => $node_type, 'title' => $this->getRandom()->sentences(mt_rand(1, $results['title_length']), TRUE), 'uid' => $uid, 'revision' => mt_rand(0, 1), 'status' => TRUE, 'promote' => mt_rand(0, 1), 'created' => REQUEST_TIME - mt_rand(0, $results['time_range']), 'langcode' => $this->getLangcode($results))); // A flag to let hook_node_insert() implementations know that this is a // generated node. $node->devel_generate = $results; // Populate all fields with sample values. $this->populateFields($node); // See devel_generate_node_insert() for actions that happen before and after // this save. $node->save(); }
/** * Creates or loads an entity. * * @param \Drupal\migrate\Row $row * The row object. * @param array $old_destination_id_values * The old destination IDs. * * @return \Drupal\Core\Entity\EntityInterface * The entity we are importing into. */ protected function getEntity(Row $row, array $old_destination_id_values) { $entity_id = reset($old_destination_id_values) ?: $this->getEntityId($row); if (!empty($entity_id) && ($entity = $this->storage->load($entity_id))) { $this->updateEntity($entity, $row); } else { // Attempt to ensure we always have a bundle. if ($bundle = $this->getBundle($row)) { $row->setDestinationProperty($this->getKey('bundle'), $bundle); } // Stubs might need some required fields filled in. if ($row->isStub()) { $this->processStubRow($row); } $entity = $this->storage->create($row->getDestination()); $entity->enforceIsNew(); } return $entity; }
/** * Creates or loads an entity. * * @param \Drupal\migrate\Row $row * The row object. * @param array $old_destination_id_values * The old destination ids. * * @return \Drupal\Core\Entity\EntityInterface * The entity we're importing into. */ protected function getEntity(Row $row, array $old_destination_id_values) { $entity_id = $old_destination_id_values ? reset($old_destination_id_values) : $row->getDestinationProperty($this->getKey('id')); if (!empty($entity_id) && ($entity = $this->storage->load($entity_id))) { $this->updateEntity($entity, $row); } else { $values = $row->getDestination(); // Stubs might not have the bundle specified. if ($row->stub()) { $bundle_key = $this->getKey('bundle'); if ($bundle_key && !isset($values[$bundle_key])) { $values[$bundle_key] = reset($this->bundles); } } $entity = $this->storage->create($values); $entity->enforceIsNew(); } return $entity; }