/** * Override MinkContext::fixStepArgument(). * * Make it possible to use [random]. * If you want to use the previous random value [random:1]. * Also, allow newlines in arguments. */ public function fixStepArgument($argument) { // Token replace the argument. static $random = array(); for ($start = 0; ($start = strpos($argument, '[', $start)) !== FALSE;) { $end = strpos($argument, ']', $start); if ($end === FALSE) { break; } $random_generator = new Random(); $name = substr($argument, $start + 1, $end - $start - 1); if ($name == 'random') { $this->vars[$name] = $random_generator->name(8); $random[] = $this->vars[$name]; } elseif (substr($name, 0, 7) == 'random:') { $num = substr($name, 7); if (is_numeric($num) && $num <= count($random)) { $this->vars[$name] = $random[count($random) - $num]; } } if (isset($this->vars[$name])) { $argument = substr_replace($argument, $this->vars[$name], $start, $end - $start + 1); $start += strlen($this->vars[$name]); } else { $start = $end + 1; } } return $argument; }
/** * {@inheritDoc} */ public function roleCreate(array $permissions) { // Both machine name and permission title are allowed. $all_permissions = $this->getAllPermissions(); foreach ($permissions as $key => $name) { if (!isset($all_permissions[$name])) { $search = array_search($name, $all_permissions); if (!$search) { throw new \RuntimeException(sprintf("No permission '%s' exists.", $name)); } $permissions[$key] = $search; } } // Create new role. $role = new \stdClass(); $role->name = $this->random->name(8); user_role_save($role); user_role_grant_permissions($role->rid, $permissions); if ($role && !empty($role->rid)) { $count = db_query('SELECT COUNT(*) FROM {role_permission} WHERE rid = :rid', array(':rid' => $role->rid))->fetchField(); if ($count == count($permissions)) { return $role->rid; } else { return FALSE; } } else { return FALSE; } }
/** * {@inheritDoc} */ public function roleCreate(array $permissions) { // Generate a random, lowercase machine name. $rid = strtolower($this->random->name(8, TRUE)); // Generate a random label. $name = trim($this->random->name(8, TRUE)); // Check the all the permissions strings are valid. if (!$this->checkPermissions($permissions)) { throw new \RuntimeException('All permissions are not valid.'); } // Create new role. $role = entity_create('user_role', array('id' => $rid, 'label' => $name)); $result = $role->save(); if ($result === SAVED_NEW) { // Grant the specified permissions to the role, if any. if (!empty($permissions)) { user_role_grant_permissions($role->id(), $permissions); // TODO: Fix this. /*$assigned_permissions = db_query('SELECT permission FROM {role_permission} WHERE rid = :rid', array(':rid' => $role->id()))->fetchCol(); $missing_permissions = array_diff($permissions, $assigned_permissions); if ($missing_permissions) { return FALSE; }*/ } return $role->id(); } else { return FALSE; } }
/** * {@inheritdoc} */ public function render(ResultRow $values) { // Return a random text, here you can include your custom logic. // Include any namespace required to call the method required to generte the // output desired $random = new Random(); return $random->name(); }
/** * {@inheritdoc} */ protected function prepareEntity() { if (empty($this->entity->name->value)) { // Assign a random name to new EntityTest entities, to avoid repetition in // tests. $random = new Random(); $this->entity->name->value = $random->name(); } }
/** * {@inheritdoc} */ public static function migrateDumpAlter(TestBase $test) { // Creates a random filename and updates the source database. $random = new Random(); $temp_directory = $test->getTempFilesDirectory(); file_prepare_directory($temp_directory, FILE_CREATE_DIRECTORY); static::$tempFilename = $test->getDatabasePrefix() . $random->name() . '.jpg'; $file_path = $temp_directory . '/' . static::$tempFilename; file_put_contents($file_path, ''); Database::getConnection('default', 'migrate')->update('files')->condition('fid', 6)->fields(array('filename' => static::$tempFilename, 'filepath' => $file_path))->execute(); return static::$tempFilename; }
/** * Implements CoreInterface::roleCreate(). */ public function roleCreate(array $permissions) { // Verify permissions exist. $all_permissions = module_invoke_all('perm'); foreach ($permissions as $name) { $search = array_search($name, $all_permissions); if (!$search) { throw new \RuntimeException(sprintf("No permission '%s' exists.", $name)); } } // Create new role. $name = $this->random->name(8); db_query("INSERT INTO {role} SET name = '%s'", $name); // Add permissions to role. $rid = db_last_insert_id('role', 'rid'); db_query("INSERT INTO {permission} (rid, perm) VALUES (%d, '%s')", $rid, implode(', ', $permissions)); return $rid; }
/** * Test views base url field. */ function testViewsBaseUrlField() { global $base_url; $random = new Random(); /** @var \Drupal\Core\Render\RendererInterface $renderer */ $renderer = $this->container->get('renderer'); // Create 10 nodes. $this->drupalLogin($this->adminUser); $this->nodes = array(); for ($i = 1; $i <= 10; $i++) { // Create node. $title = $random->name(); $image = current($this->drupalGetTestFiles('image')); $edit = array('title[0][value]' => $title, 'files[field_image_0]' => drupal_realpath($image->uri)); $this->drupalPostForm('node/add/article', $edit, t('Save')); $this->drupalPostForm(NULL, array('field_image[0][alt]' => $title), t('Save')); $this->nodes[$i] = $this->drupalGetNodeByTitle($title); // Create path alias. $path = array('source' => 'node/' . $this->nodes[$i]->id(), 'alias' => "content/{$title}"); \Drupal::service('path.alias_storage')->save('/node/' . $this->nodes[$i]->id(), "/content/{$title}"); } $this->drupalLogout(); $this->drupalGet('views-base-url-test'); $this->assertResponse(200); // Check whether there are ten rows. $rows = $this->xpath('//div[contains(@class,"view-views-base-url-test")]/div[@class="view-content"]/div[contains(@class,"views-row")]'); $this->assertEqual(count($rows), 10, t('There are 10 rows')); // We check for at least one views result that link is properly rendered as // image. $node = $this->nodes[1]; $field = $node->get('field_image'); $file = $field->entity; $value = $field->getValue(); $image = array('#theme' => 'image', '#uri' => $file->getFileUri(), '#alt' => $value[0]['alt'], '#attributes' => array('width' => $value[0]['width'], 'height' => $value[0]['height'])); $url = Url::fromUri($base_url . '/' . \Drupal::service('path.alias_manager')->getAliasByPath('/node/' . $node->id()), array('attributes' => array('class' => 'views-base-url-test', 'title' => $node->getTitle(), 'rel' => 'rel-attribute', 'target' => '_blank'), 'fragment' => 'new', 'query' => array('destination' => 'node'))); $link = \Drupal::l(SafeMarkup::format(str_replace("\n", NULL, $renderer->renderRoot($image))), $url); $this->verbose($link); $this->assertRaw($link, t('Views base url rendered as link image')); }
/** * {@inheritdoc} */ public static function generateSampleValue(FieldDefinitionInterface $field_definition) { $random = new Random(); $settings = $field_definition->getSettings(); // Prepare destination. $dirname = static::doGetUploadLocation($settings); file_prepare_directory($dirname, FILE_CREATE_DIRECTORY); // Generate a file entity. $destination = $dirname . '/' . $random->name(10, TRUE) . '.txt'; $data = $random->paragraphs(3); $file = file_save_data($data, $destination, FILE_EXISTS_ERROR); $values = array('target_id' => $file->id(), 'display' => (int) $settings['display_default'], 'description' => $random->sentences(10)); return $values; }
/** * {@inheritdoc} */ public static function generateSampleValue(FieldDefinitionInterface $field_definition) { $random = new Random(); if ($field_definition->getItemDefinition()->getSetting('link_type') & LinkItemInterface::LINK_EXTERNAL) { // Set of possible top-level domains. $tlds = array('com', 'net', 'gov', 'org', 'edu', 'biz', 'info'); // Set random length for the domain name. $domain_length = mt_rand(7, 15); switch ($field_definition->getSetting('title')) { case DRUPAL_DISABLED: $values['title'] = ''; break; case DRUPAL_REQUIRED: $values['title'] = $random->sentences(4); break; case DRUPAL_OPTIONAL: // In case of optional title, randomize its generation. $values['title'] = mt_rand(0, 1) ? $random->sentences(4) : ''; break; } $values['uri'] = 'http://www.' . $random->word($domain_length) . '.' . $tlds[mt_rand(0, sizeof($tlds) - 1)]; } else { $values['uri'] = 'base:' . $random->name(mt_rand(1, 64)); } return $values; }
/** * {@inheritdoc} */ public static function generateSampleValue(FieldDefinitionInterface $field_definition) { $random = new Random(); $values['value'] = $random->name() . '@example.com'; return $values; }
/** * Tests random name generation if uniqueness is not enforced. * * @covers ::name */ public function testRandomNameNonUnique() { // There are fewer than 100 possibilities if we were forcing uniqueness so // exception would occur. $random = new Random(); for ($i = 0; $i <= 100; $i++) { $random->name(1); } $this->assertTrue(TRUE, 'No exception thrown when uniqueness is not enforced.'); }
/** * @Given /^I log in with the One Time Login Url$/ */ public function iLogInWithTheOneTimeLoginUrl() { if ($this->loggedIn()) { $this->logOut(); } $random = new Random(); // Create user (and project) $user = (object) array('name' => $random->name(8), 'pass' => $random->name(16), 'role' => 'authenticated user'); $user->mail = "{$user->name}@example.com"; // Create a new user. $this->getDriver()->userCreate($user); $this->users[$user->name] = $this->user = $user; $base_url = rtrim($this->locatePath('/'), '/'); $login_link = $this->getMainContext()->getDriver('drush')->drush('uli', array("'{$user->name}'", '--browser=0', "--uri={$base_url}")); // Trim EOL characters. Required or else visiting the link won't work. $login_link = trim($login_link); $login_link = str_replace("/login", '', $login_link); $this->getSession()->visit($this->locatePath($login_link)); return TRUE; }
/** * {@inheritdoc} */ public static function generateSampleValue(FieldDefinitionInterface $field_definition) { $random = new Random(); $settings = $field_definition->getSettings(); // Generate a file entity. $destination = $settings['uri_scheme'] . '://' . $settings['file_directory'] . $random->name(10, TRUE) . '.txt'; $data = $random->paragraphs(3); $file = file_save_data($data, $destination, FILE_EXISTS_ERROR); $values = array('target_id' => $file->id(), 'display' => (int) $settings['display_default'], 'description' => $random->sentences(10)); return $values; }
/** * Return a valid mail address. */ protected function getMailCreds() { if (empty($this->mailCreds)) { $creds = $this->fetchUserPassword('drupal', 'mail'); if ($creds) { // Split the parameter based creds on a / separator. $creds_array = explode('/', $creds); $creds_array += array(2 => 'gmail.com', 3 => 'imap.gmail.com:993'); // Create keyed array of mail credentials. $this->mailCreds = array('user' => $creds_array[0], 'pass' => $creds_array[1], 'host' => $creds_array[2], 'imap' => $creds_array[3]); $this->mailCreds['email'] = $this->mailCreds['user'] . '+' . Random::name(8) . '@' . $this->mailCreds['host']; } } return $this->mailCreds; }
/** * Fill commerce address form fields in a single step. */ private function fillCommerceAddress($args, $type) { // Replace <random> or member <property> token if is set for any field foreach ($args as $delta => $arg) { if (preg_match("/^<random>\$/", $arg, $matches)) { $random = new Random(); $args[$delta] = $random->name(); } } // Need to manually fill country to trigger the AJAX refresh of fields for given country $country_field = $this->fixStepArgument("{$type}[commerce_customer_address][und][0][country]"); $country_value = $this->fixStepArgument($args[4]); $this->getSession()->getPage()->fillField($country_field, $country_value); $this->iWaitForAjaxToFinish(); return array(new Given("I fill in \"{$type}[commerce_customer_address][und][0][locality]\" with \"{$args['1']}\""), new Given("I fill in \"{$type}[commerce_customer_address][und][0][administrative_area]\" with \"{$args['2']}\""), new Given("I fill in \"{$type}[commerce_customer_address][und][0][postal_code]\" with \"{$args['3']}\""), new Given("I fill in \"{$type}[commerce_customer_address][und][0][thoroughfare]\" with \"{$args['0']}\"")); }