You are here

private function IpAddress::parse in IP address fields 8

Same name and namespace in other branches
  1. 2.0.x src/IpAddress.php \Drupal\field_ipaddress\IpAddress::parse()

Find if the value given is an IP, IP range, or other.

1 call to IpAddress::parse()
IpAddress::__construct in src/IpAddress.php
On construction, parse the given value.

File

src/IpAddress.php, line 128

Class

IpAddress
IpTools class.

Namespace

Drupal\field_ipaddress

Code

private function parse($value) {
  $value = trim(str_replace(' ', '', $value));

  // Check if this is a simple range.
  if (strpos($value, '-') !== FALSE) {

    // Break its parts apart.
    list($start, $end) = explode('-', $value, 2);
    if (!$this
      ->isIpAddress($start) || !$this
      ->isIpAddress($end) || $this
      ->isIpV6($start) && !$this
      ->isIpV6($end) || $this
      ->isIpV4($start) && !$this
      ->isIpV4($end)) {

      // Return false on failure.
      return FALSE;
    }

    // Simple is ... simple, assign the bounds.
    $this->start = $start;
    $this->end = $end;
    $this->family = $this
      ->getFamily($start);
    $this->type = self::IP_RANGE_SIMPLE;
  }
  elseif (strpos($value, '/') !== FALSE) {

    // Break its parts apart.
    list($ip, $prefix) = explode('/', $value, 2);
    if (!$this
      ->isIpAddress($ip) || !is_numeric($prefix) || $prefix <= 0) {
      return FALSE;
    }
    $this->family = $this
      ->getFamily($ip);

    // Check that the prefix is not larger than address.
    if ($this->family == self::IP_FAMILY_4 && $prefix > 32 || $this->family == self::IP_FAMILY_6 && $prefix > 128) {
      return FALSE;
    }
    $this->type = self::IP_RANGE_CIDR;

    // Calculate CIDR address bounds.
    if ($this->family == self::IP_FAMILY_4) {
      $this
        ->calcCidr4($ip, $prefix);
    }
    else {
      $this
        ->calcCidr6($ip, $prefix);
    }
  }
  elseif ($this
    ->isIpAddress($value)) {
    $this->type = self::IP_RANGE_NONE;
    $this->family = $this
      ->getFamily($value);
    $this->start = $value;
    $this->end = $value;
  }
  else {
    return FALSE;
  }
}