/** * {@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; }
/** * 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 static function generateSampleValue(FieldDefinitionInterface $field_definition) { $random = new Random(); $max = $field_definition->getSetting('max_length'); $values['value'] = $random->word(mt_rand(1, $max)); return $values; }
/** * {@inheritdoc} */ public static function generateSampleValue(FieldDefinitionInterface $field_definition) { // Set random length for the path. $domain_length = mt_rand(7, 15); $random = new Random(); $values['path'] = 'http://www.' . $random->word($domain_length); return $values; }
/** * {@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; }
/** * {@inheritdoc} */ public static function generateSampleValue(FieldDefinitionInterface $field_definition) { $random = new Random(); $settings = $field_definition->getSettings(); if (empty($settings['max_length'])) { // Textarea handling $value = $random->paragraphs(); } else { // Textfield handling. $value = substr($random->sentences(mt_rand(1, $settings['max_length'] / 3), FALSE), 0, $settings['max_length']); } $values = array('value' => $value, 'summary' => $value, 'format' => filter_fallback_format()); return $values; }
/** * {@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; } }
/** * Provides test data for testPhpTransliterationWithAlter. * * @return array */ public function providerTestPhpTransliterationWithAlter() { $random_generator = new Random(); $random = $random_generator->string(10); // Make some strings with two, three, and four-byte characters for testing. // Note that the 3-byte character is overridden by the 'kg' language. $two_byte = 'Ä Ö Ü Å Ø äöüåøhello'; // These are two Gothic alphabet letters. See // http://en.wikipedia.org/wiki/Gothic_alphabet // They are not in our tables, but should at least give us '?' (unknown). $five_byte = html_entity_decode('𐌰𐌸', ENT_NOQUOTES, 'UTF-8'); // Five-byte characters do not work in MySQL, so make a printable version. $five_byte_printable = '𐌰𐌸'; $cases = array(array('zz', $two_byte, 'Z O U A O aouaohello'), array('zz', $random, $random), array('zz', $five_byte, 'ATh', $five_byte_printable)); return $cases; }
/** * Provides data for self::testPhpTransliteration(). * * @return array * An array of arrays, each containing the parameters for * self::testPhpTransliteration(). */ public function providerTestPhpTransliteration() { $random_generator = new Random(); $random = $random_generator->string(10); // Make some strings with two, three, and four-byte characters for testing. // Note that the 3-byte character is overridden by the 'kg' language. $two_byte = 'Ä Ö Ü Å Ø äöüåøhello'; // This is a Cyrrillic character that looks something like a u. See // http://www.unicode.org/charts/PDF/U0400.pdf $three_byte = html_entity_decode('ц', ENT_NOQUOTES, 'UTF-8'); // This is a Canadian Aboriginal character like a triangle. See // http://www.unicode.org/charts/PDF/U1400.pdf $four_byte = html_entity_decode('ᐑ', ENT_NOQUOTES, 'UTF-8'); // These are two Gothic alphabet letters. See // http://wikipedia.org/wiki/Gothic_alphabet // They are not in our tables, but should at least give us '?' (unknown). $five_byte = html_entity_decode('𐌰𐌸', ENT_NOQUOTES, 'UTF-8'); return array(array('en', $random, $random), array('fr', $random, $random), array('fr', $three_byte, 'c'), array('fr', $four_byte, 'wii'), array('en', $five_byte, '??'), array('en', $two_byte, 'A O U A O aouaohello'), array('de', $two_byte, 'Ae Oe Ue A O aeoeueaohello'), array('de', $random, $random), array('dk', $two_byte, 'A O U Aa Oe aouaaoehello'), array('dk', $random, $random), array('kg', $three_byte, 'ts'), array('tr', 'Abayı serdiler bize. Söyleyeceğim yüzlerine. Sanırım hepimiz aynı şeyi düşünüyoruz.', 'Abayi serdiler bize. Soyleyecegim yuzlerine. Sanirim hepimiz ayni seyi dusunuyoruz.'), array('en', chr(0xf8) . chr(0x80) . chr(0x80) . chr(0x80) . chr(0x80), '?'), array('de', $two_byte, 'Ae Oe', '?', 5)); }
/** * 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')); }
/** * 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; }
/** * {@inheritdoc} */ public static function generateSampleValue(FieldDefinitionInterface $field_definition) { $random = new Random(); $values['alias'] = str_replace(' ', '-', strtolower($random->sentences(3))); return $values; }
/** * {@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; }
/** * Tries to claim a payment once. * * @param integer $payment_id * * @return string|false * An acquisition code to acquire the payment with on success, or FALSE if * the payment could not be claimed. */ protected function tryClaimPaymentOnce($payment_id) { $acquisition_code = $this->randomGenerator->string(255); $count = $this->database->update('payment_queue', array('return' => Database::RETURN_AFFECTED))->condition('claimed', time() - $this->getClaimExpirationPeriod(), '<')->condition('payment_id', $payment_id)->condition('queue_id', $this->queueId)->fields(array('acquisition_code' => $acquisition_code, 'claimed' => time()))->execute(); return $count ? $acquisition_code : FALSE; }
/** * 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; }
/** * {@inheritdoc} */ public function validate($text = NULL) { $random = new Random(); $errors = []; // Check if the object properties are set correctly. if (!$this->getEncryptionMethodId()) { $errors[] = $this->t('No encryption method selected.'); } if (!$this->getEncryptionKeyId()) { $errors[] = $this->t('No encryption key selected.'); } // If the properties are set, continue validation. if ($this->getEncryptionMethodId() && $this->getEncryptionKeyId()) { // Check if the linked encryption method is valid. $encryption_method = $this->getEncryptionMethod(); if (!$encryption_method) { $errors[] = $this->t('The encryption method linked to this encryption profile does not exist.'); } // Check if the linked encryption key is valid. $selected_key = $this->getEncryptionKey(); if (!$selected_key) { $errors[] = $this->t('The key linked to this encryption profile does not exist.'); } // If the encryption method and key are valid, continue validation. if (empty($errors)) { // Check if the selected key type matches encryption method settings. $allowed_key_types = $encryption_method->getPluginDefinition()['key_type']; if (!empty($allowed_key_types)) { $selected_key_type = $selected_key->getKeyType(); if (!in_array($selected_key_type->getPluginId(), $allowed_key_types)) { $errors[] = $this->t('The selected key cannot be used with the selected encryption method.'); } } // Check if encryption method dependencies are met. $encryption_method = $this->getEncryptionMethod(); if (!$text) { $text = $random->string(); } $dependency_errors = $encryption_method->checkDependencies($text, $selected_key->getKeyValue()); $errors = array_merge($errors, $dependency_errors); } } return $errors; }
/** * 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']}\"")); }
/** * @Given /^I am viewing (?:a|an) "([^"]*)" node$/ * @Given /^I create (?:a|an) "([^"]*)" node$/ * * This overrides the parent createNode() method, allowing node properties * to be passes via $properties argument. * * @override */ public function createNode($type, $properties = array()) { $node = (object) array('title' => Random::string(25), 'type' => $type, 'uid' => 1); if ($properties) { foreach ($properties as $key => $value) { $node->{$key} = $value; } } $this->dispatcher->dispatch('beforeNodeCreate', new EntityEvent($this, $node)); $saved = $this->getDriver()->createNode($node); $this->dispatcher->dispatch('afterNodeCreate', new EntityEvent($this, $saved)); $this->nodes[] = $saved; // Set internal page on the new node. $this->getSession()->visit($this->locatePath('/node/' . $saved->nid)); return $saved; }
/** * {@inheritdoc} */ public static function generateSampleValue(FieldDefinitionInterface $field_definition) { $random = new Random(); $values['value'] = $random->name() . '@example.com'; return $values; }
/** * Tests random string validation callbacks. * * @covers ::string */ public function testRandomStringValidator() { $random = new Random(); $this->firstStringGenerated = ''; $str = $random->string(1, TRUE, array($this, '_RandomStringValidate')); $this->assertNotEquals($this->firstStringGenerated, $str); }
/** * {@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(); $settings = $field_definition->getSettings(); static $images = array(); $min_resolution = empty($settings['min_resolution']) ? '100x100' : $settings['min_resolution']; $max_resolution = empty($settings['max_resolution']) ? '600x600' : $settings['max_resolution']; $extensions = array_intersect(explode(' ', $settings['file_extensions']), array('png', 'gif', 'jpg', 'jpeg')); $extension = array_rand(array_combine($extensions, $extensions)); // Generate a max of 5 different images. if (!isset($images[$extension][$min_resolution][$max_resolution]) || count($images[$extension][$min_resolution][$max_resolution]) <= 5) { $tmp_file = drupal_tempnam('temporary://', 'generateImage_'); $destination = $tmp_file . '.' . $extension; file_unmanaged_move($tmp_file, $destination, FILE_CREATE_DIRECTORY); if ($path = $random->image(drupal_realpath($destination), $min_resolution, $max_resolution)) { $image = File::create(); $image->setFileUri($path); $image->setOwnerId(\Drupal::currentUser()->id()); $image->setMimeType(\Drupal::service('file.mime_type.guesser')->guess($path)); $image->setFileName(drupal_basename($path)); $destination_dir = static::doGetUploadLocation($settings); file_prepare_directory($destination_dir, FILE_CREATE_DIRECTORY); $destination = $destination_dir . '/' . basename($path); $file = file_move($image, $destination, FILE_CREATE_DIRECTORY); $images[$extension][$min_resolution][$max_resolution][$file->id()] = $file; } else { return array(); } } else { // Select one of the images we've already generated for this field. $image_index = array_rand($images[$extension][$min_resolution][$max_resolution]); $file = $images[$extension][$min_resolution][$max_resolution][$image_index]; } list($width, $height) = getimagesize($file->getFileUri()); $values = array('target_id' => $file->id(), 'alt' => $random->sentences(4), 'title' => $random->sentences(4), 'width' => $width, 'height' => $height); return $values; }
/** * @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(); $values['value'] = $random->paragraphs(); return $values; }
/** * {@inheritdoc} */ public static function generateSampleValue(FieldDefinitionInterface $field_definition) { $random = new Random(); $values['value'] = $random->word(mt_rand(1, 50)); return $values; }