CoreFiles by mySites.guru
IPv6Address.php60 lines, 1,676 bytes, from Joomla_6.2.0-beta2-Beta-Full_Package.zip
Raw History Compare with 6.2.0-beta1
md5
c58843229f4569954b857c7b69aedb91
sha1
5b82fe16b7175f6b7d1287222f64ae70932cebb2
sha256
8debd0a4309ecc9267eb4ca27c057eb57ee716adc14f4d593b33465f3923188a
<?php

declare(strict_types=1);

namespace SpomkyLabs\Pki\X509\GeneralName;

use function array_slice;
use function count;
use function sprintf;
use UnexpectedValueException;

final class IPv6Address extends IPAddress
{
    public static function create(string $ip, ?string $mask = null): self
    {
        return new self($ip, $mask);
    }

    /**
     * Initialize from octets.
     */
    public static function fromOctets(string $octets): self
    {
        $mask = null;
        $words = unpack('n*', $octets);
        $words = $words === false ? [] : $words;
        switch (count($words)) {
            case 8:
                $ip = self::wordsToIPv6String($words);
                break;
            case 16:
                $ip = self::wordsToIPv6String(array_slice($words, 0, 8));
                $mask = self::wordsToIPv6String(array_slice($words, 8, 8));
                break;
            default:
                throw new UnexpectedValueException('Invalid IPv6 octet length.');
        }
        return self::create($ip, $mask);
    }

    /**
     * Convert an array of 16 bit words to an IPv6 string representation.
     *
     * @param int[] $words
     */
    protected static function wordsToIPv6String(array $words): string
    {
        $groups = array_map(static fn ($word) => sprintf('%04x', $word), $words);
        return implode(':', $groups);
    }

    protected function octets(): string
    {
        $words = array_map(hexdec(...), explode(':', $this->ip));
        if (isset($this->mask)) {
            $words = array_merge($words, array_map(hexdec(...), explode(':', $this->mask)));
        }
        return pack('n*', ...$words);
    }
}

The same content is in 11 releases, Joomla 6.2.0-alpha2 to 6.3.0-alpha1. See them all, or every version of this file.