You are here

public static function IpAddressField::generateSampleValue in IP address fields 8

Same name and namespace in other branches
  1. 2.0.x src/Plugin/Field/FieldType/IpAddressField.php \Drupal\field_ipaddress\Plugin\Field\FieldType\IpAddressField::generateSampleValue()

Generates placeholder field values.

Useful when populating site with placeholder content during site building or profiling.

Parameters

\Drupal\Core\Field\FieldDefinitionInterface $field_definition: The field definition.

Return value

array An associative array of values.

Overrides FieldItemBase::generateSampleValue

File

src/Plugin/Field/FieldType/IpAddressField.php, line 86

Class

IpAddressField
Plugin implementation of the 'ipaddress' field type.

Namespace

Drupal\field_ipaddress\Plugin\Field\FieldType

Code

public static function generateSampleValue(FieldDefinitionInterface $field_definition) {

  // First random i IPv4 or IPv6.
  $family = rand(0, 1) == 1;

  // IPv6 contains 16 bytes, IPv4 contains 4 bytes.
  $bytes = $family == 1 ? 16 : 4;

  // Use a built in PHP function to generate random bytes.
  $values['ip_start'] = openssl_random_pseudo_bytes($bytes);

  // Extract first part excluding last byte.
  $values['ip_end'] = substr($values['ip_start'], 0, $bytes - 1);
  $last_byte = substr($values['ip_start'], -1);
  $from_last_number = end(unpack('C', $last_byte));
  $to_last_number = rand($from_last_number, 255);

  // Add last number.
  $values['ip_end'] .= pack('C', $to_last_number);
  return $values;
}