You are here

public static function MobileNumberItem::generateSampleValue in Mobile Number 8

Same name and namespace in other branches
  1. 2.0.x src/Plugin/Field/FieldType/MobileNumberItem.php \Drupal\mobile_number\Plugin\Field\FieldType\MobileNumberItem::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/MobileNumberItem.php, line 315

Class

MobileNumberItem
Plugin implementation of the 'mobile_number' field type.

Namespace

Drupal\mobile_number\Plugin\Field\FieldType

Code

public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
  static $last_numbers = [];

  /** @var \Drupal\mobile_number\MobileNumberUtilInterface $util */
  $util = \Drupal::service('mobile_number.util');
  $settings = [
    'verify' => $util
      ->isSmsEnabled() ? $util::MOBILE_NUMBER_VERIFY_OPTIONAL : $util::MOBILE_NUMBER_VERIFY_NONE,
    'countries' => [],
  ];
  $country = array_rand($util
    ->getCountryOptions($settings['countries']));
  $last = !empty($last_numbers[$country]) ? $last_numbers[$country] : [];
  $mobile_number = NULL;
  if (!$last) {
    $last['count'] = 0;
    $last['example'] = ($number = $util
      ->libUtil()
      ->getExampleNumberForType($country, 1)) ? $number
      ->getNationalNumber() : NULL;
  }
  $example = $last['example'];
  $count = $last['count'];
  if ($example) {
    while (strlen($count) <= strlen($example) && !$mobile_number) {
      $number_length = strlen($example);
      $number = substr($example, 0, $number_length - strlen($count)) . $count;
      if (substr($count, 0, 1) != substr($example, strlen($count) - 1, 1)) {
        $mobile_number = $util
          ->getMobileNumber($number, $country);
      }
      $count = ($count + 1) % pow(10, strlen($example));
    }
  }
  $value = [];
  if ($mobile_number) {
    $value = [
      'value' => $util
        ->getCallableNumber($mobile_number),
    ];
    switch ($settings['verify']) {
      case $util::MOBILE_NUMBER_VERIFY_NONE:
        $value['verified'] = 0;
        break;
      case $util::MOBILE_NUMBER_VERIFY_OPTIONAL:
        $value['verified'] = rand(0, 1);
        break;
      case $util::MOBILE_NUMBER_VERIFY_REQUIRED:
        $value['verified'] = 1;
        break;
    }
  }
  return $value;
}