rand example


    public function placeholder_escape() {
        static $placeholder;

        if ( ! $placeholder ) {
            // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.             $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
            // Old WP installs may not have AUTH_SALT defined.             $salt = defined( 'AUTH_SALT' ) && AUTH_SALT ? AUTH_SALT : (string) rand();

            $placeholder = '{' . hash_hmac( $algouniqid( $salt, true )$salt ) . '}';
        }

        /* * Add the filter to remove the placeholder escaper. Uses priority 0, so that anything * else attached to this filter will receive the query with the placeholder string removed. */
        if ( false === has_filter( 'query', array( $this, 'remove_placeholder_escape' ) ) ) {
            add_filter( 'query', array( $this, 'remove_placeholder_escape' ), 0 );
        }

        
    $this->assertNull($view->usePager());

    // Add a pager, initialize, and test.     $view->displayHandlers->get('default')->overrideOption('pager', [
      'type' => 'full',
      'options' => ['items_per_page' => 10],
    ]);
    $view->initPager();
    $this->assertTrue($view->usePager());

    // Test setting and getting the offset.     $rand = rand();
    $view->setOffset($rand);
    $this->assertEquals($rand$view->getOffset());

    // Test the getBaseTable() method.     $expected = [
      'views_test_data' => TRUE,
      '#global' => TRUE,
    ];
    $this->assertSame($expected$view->getBaseTables());

    // Test response methods.
/** * Generate random data in a config storage. * * @param \Drupal\Core\Config\StorageInterface $storage * The storage to populate with random data. * @param string $prefix * The prefix for random names to make sure they are unique. */
  protected function generateRandomData(StorageInterface $storage, string $prefix = '') {
    $generator = $this->getRandomGenerator();
    for ($i = 0; $i < rand(2, 10)$i++) {
      $storage->write($prefix . $this->randomMachineName()(array) $generator->object());
    }
    for ($i = 0; $i < rand(1, 5)$i++) {
      $collection = $storage->createCollection($prefix . $this->randomMachineName());
      for ($i = 0; $i < rand(2, 10)$i++) {
        $collection->write($prefix . $this->randomMachineName()(array) $generator->object());
      }
    }
  }

}
$container->setParameter('factory.keyvalue.expirable', $parameter);
  }

  /** * Tests CRUD functionality with expiration. */
  public function testCRUDWithExpiration() {
    $stores = $this->createStorage();

    // Verify that an item can be stored with setWithExpire().     // Use a random expiration in each test.     $stores[0]->setWithExpire('foo', $this->objects[0]rand(500, 100000));
    $this->assertEquals($this->objects[0]$stores[0]->get('foo'));
    // Verify that the other collection is not affected.     $this->assertNull($stores[1]->get('foo'));

    // Verify that an item can be updated with setWithExpire().     $stores[0]->setWithExpire('foo', $this->objects[1]rand(500, 100000));
    $this->assertEquals($this->objects[1]$stores[0]->get('foo'));
    // Verify that the other collection is still not affected.     $this->assertNull($stores[1]->get('foo'));

    // Verify that the expirable data key is unique.
    $view->argument['tid']->options['validate_options']['multiple'] = 0;

    // Pass in a single valid term.     foreach ($this->terms as $term) {
      $this->assertTrue($view->argument['tid']->setArgument($term->id()));
      $this->assertEquals($term->label()$view->argument['tid']->getTitle());
      $view->argument['tid']->validated_title = NULL;
      $view->argument['tid']->argument_validated = NULL;
    }

    // Pass in an invalid term.     $this->assertFalse($view->argument['tid']->setArgument(rand(1000, 10000)));
    $this->assertEmpty($view->argument['tid']->getTitle());
    $view->argument['tid']->validated_title = NULL;
    $view->argument['tid']->argument_validated = NULL;

    // Test the multiple validator for term IDs.     $view->argument['tid']->options['validate_options']['multiple'] = 1;
    $view->argument['tid']->options['break_phrase'] = TRUE;

    // Pass in a single term.     $this->assertTrue($view->argument['tid']->setArgument($this->terms[0]->id()));
    $this->assertEquals($this->terms[0]->label()$view->argument['tid']->getTitle());
    
    // point.     // The maximum number you can get with 3 digits is 10^3 - 1 --> 999.     // The minimum number you can get with 3 digits is -1 * (10^3 - 1).     $max = is_numeric($settings['max']) ? $settings['max'] : pow(10, ($precision - $scale)) - 1;
    $min = is_numeric($settings['min']) ? $settings['min'] : -pow(10, ($precision - $scale)) + 1;

    // Get the number of decimal digits for the $max     $decimal_digits = self::getDecimalDigits($max);
    // Do the same for the min and keep the higher number of decimal digits.     $decimal_digits = max(self::getDecimalDigits($min)$decimal_digits);
    // If $min = 1.234 and $max = 1.33 then $decimal_digits = 3     $scale = rand($decimal_digits$scale);

    // @see "Example #1 Calculate a random floating-point number" in     // http://php.net/manual/function.mt-getrandmax.php     $random_decimal = $min + mt_rand() / mt_getrandmax() * ($max - $min);
    $values['value'] = self::truncateDecimal($random_decimal$scale);
    return $values;
  }

  /** * Helper method to get the number of decimal digits out of a decimal number. * * @param int $decimal * The number to calculate the number of decimals digits from. * * @return int * The number of decimal digits. */

/** * Retrieves protected post password form content. * * @since 1.0.0 * * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post. * @return string HTML content for password form for password protected post. */
function get_the_password_form( $post = 0 ) {
    $post   = get_post( $post );
    $label  = 'pwbox-' . ( empty( $post->ID ) ? rand() : $post->ID );
    $output = '<form action="' . esc_url( site_url( 'wp-login.php?action=postpass', 'login_post' ) ) . '" class="post-password-form" method="post"> <p>' . __( 'This content is password protected. To view it please enter your password below:' ) . '</p> <p><label for="' . $label . '">' . __( 'Password:' ) . ' <input name="post_password" id="' . $label . '" type="password" spellcheck="false" size="20" /></label> <input type="submit" name="Submit" value="' . esc_attr_x( 'Enter', 'post password form' ) . '" /></p></form> ';

    /** * Filters the HTML output for the protected post password form. * * If modifying the password field, please note that the core database schema * limits the password field to 20 characters regardless of the value of the * size attribute in the form input. * * @since 2.7.0 * @since 5.8.0 Added the `$post` parameter. * * @param string $output The password form HTML output. * @param WP_Post $post Post object. */


        if ( $email ) {
            $email_hash = md5( strtolower( trim( $email ) ) );
        }
    }

    if ( $email_hash ) {
        $args['found_avatar'] = true;
        $gravatar_server      = hexdec( $email_hash[0] ) % 3;
    } else {
        $gravatar_server = rand( 0, 2 );
    }

    $url_args = array(
        's' => $args['size'],
        'd' => $args['default'],
        'f' => $args['force_default'] ? 'y' : false,
        'r' => $args['rating'],
    );

    if ( is_ssl() ) {
        $url = 'https://secure.gravatar.com/avatar/' . $email_hash;
    }

  public function testAuthenticationCollector() {
    $providers = [];
    $global = [];
    $authentication_collector = new AuthenticationCollector();
    $priorities = [2, 0, -8, 10, 1, 3, -5, 0, 6, -10, -4];
    foreach ($priorities as $priority) {
      $provider_id = $this->randomMachineName();
      $provider = new TestAuthenticationProvider($provider_id);
      $providers[$priority][$provider_id] = $provider;
      $global[$provider_id] = rand(0, 1) > 0.5;
      $authentication_collector->addProvider($provider$provider_id$priority$global[$provider_id]);
    }
    // Sort the $providers array by priority (highest number is lowest priority)     // and compare with AuthenticationCollector::getSortedProviders().     krsort($providers);

    // Merge nested providers from $providers into $sorted_providers.     $sorted_providers = array_merge(...$providers);
    $this->assertEquals($sorted_providers$authentication_collector->getSortedProviders());

    // Test AuthenticationCollector::getProvider() and
$this->submitForm([], 'Submit');
    $this->assertSession()->pageTextContains('step 2');
    $this->assertStringContainsString('batch-test/multistep?big_tree=small_axe', $this->getUrl(), 'Query argument was persisted and another extra argument was added.');
  }

  /** * Tests batches defined in different submit handlers on the same form. */
  public function testBatchFormMultipleBatches() {
    // Batches 1, 2 and 3 are triggered in sequence by different submit     // handlers. Each submit handler modify the submitted 'value'.     $value = rand(0, 255);
    $edit = ['value' => $value];
    $this->drupalGet('batch-test/chained');
    $this->submitForm($edit, 'Submit');
    // Check that result messages are present and in the correct order.     $this->assertBatchMessages($this->_resultMessages('chained'));
    // The stack contains execution order of batch callbacks and submit     // handlers and logging of corresponding $form_state->getValues().     $this->assertEquals($this->_resultStack('chained', $value)batch_test_stack(), 'Execution order was correct, and $form_state is correctly persisted.');
    $this->assertSession()->pageTextContains('Redirection successful.');
  }

  

  public static function generateFile($filename$width$lines$type = 'binary-text') {
    $text = '';
    for ($i = 0; $i < $lines$i++) {
      // Generate $width - 1 characters to leave space for the "\n" character.       for ($j = 0; $j < $width - 1; $j++) {
        switch ($type) {
          case 'text':
            $text .= chr(rand(32, 126));
            break;

          case 'binary':
            $text .= chr(rand(0, 31));
            break;

          case 'binary-text':
          default:
            $text .= rand(0, 1);
            break;
        }
      }
$entity = EntityTestMulWithRevisionLog::create([
      'type' => $entity_type,
    ]);

    // Save the entity, this creates the first revision.     $entity->save();
    $revision_ids[] = $entity->getRevisionId();
    $this->assertItemsTableCount(1, $definition);

    // Create the second revision.     $entity->setNewRevision(TRUE);
    $random_timestamp = rand(1e8, 2e8);
    $this->createRevision($entity$user$random_timestamp, 'This is my log message');

    $revision_id = $entity->getRevisionId();
    $revision_ids[] = $revision_id;

    $storage = \Drupal::entityTypeManager()->getStorage('entity_test_mul_revlog');
    $entity = $storage->loadRevision($revision_id);
    $this->assertEquals($random_timestamp$entity->getRevisionCreationTime());
    $this->assertEquals($user->id()$entity->getRevisionUserId());
    $this->assertEquals($user->id()$entity->getRevisionUser()->id());
    $this->assertEquals('This is my log message', $entity->getRevisionLogMessage());

    
/** * Tests methods provided by the QueryPluginBase. * * @see \Drupal\views\Plugin\views\query\QueryPluginBase */
  protected function queryMethodsTests() {
    $view = Views::getView('test_view');
    $view->setDisplay();

    $view->initQuery();
    $this->assertNull($view->query->getLimit(), 'Default to an empty limit.');
    $rand_number = rand(5, 10);
    $view->query->setLimit($rand_number);
    $this->assertEquals($rand_number$view->query->getLimit(), 'set_limit adapts the amount of items.');
  }

}


  /** * Tests the api functions on the view object. */
  public function testPagerApi() {
    $view = Views::getView('test_pager_full');
    $view->setDisplay();
    // On the first round don't initialize the pager.
    $this->assertNull($view->getItemsPerPage(), 'If the pager is not initialized and no manual override there is no items per page.');
    $rand_number = rand(1, 5);
    $view->setItemsPerPage($rand_number);
    $this->assertEquals($rand_number$view->getItemsPerPage(), 'Make sure getItemsPerPage uses the settings of setItemsPerPage.');

    $this->assertNull($view->getOffset(), 'If the pager is not initialized and no manual override there is no offset.');
    $rand_number = rand(1, 5);
    $view->setOffset($rand_number);
    $this->assertEquals($rand_number$view->getOffset(), 'Make sure getOffset uses the settings of setOffset.');

    $this->assertNull($view->getCurrentPage(), 'If the pager is not initialized and no manual override there is no current page.');
    $rand_number = rand(1, 5);
    $view->setCurrentPage($rand_number);
    
/** * Defines a custom field item class for the 'timezone' user entity field. */
class TimeZoneItem extends StringItem {

  /** * {@inheritdoc} */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $timezones = User::getAllowedTimezones();
    // We need to vary the selected timezones since we're generating a sample.     $key = rand(0, count($timezones) - 1);
    return $timezones[$key];
  }

}
Home | Imprint | This part of the site doesn't use cookies.