Lines 85.71% 12 / 14
Functions and Methods 80.00% 4 / 5
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
PageReference 85.71% 12 / 14 80.00% 4 / 5 9.24 0.00% 0 / 1
 __construct 100.00% 2 / 2 100.00% 1 / 1 2
 forPrevious 100.00% 1 / 1 100.00% 1 / 1 1
 forNext 100.00% 1 / 1 100.00% 1 / 1 1
 forNumber 100.00% 1 / 1 100.00% 1 / 1 1
 validateUrl 77.77% 7 / 9 0.00% 0 / 1 4.18
1<?php
2
3declare(strict_types=1);
4
5namespace Districts\Editor\UI\View;
6
7use InvalidArgumentException;
8use Uri\WhatWg\InvalidUrlException;
9use Uri\WhatWg\Url;
10
11readonly class PageReference
12{
13    private function __construct(
14        public ?string $url,
15        public string $text,
16        public bool $isCurrent,
17        public bool $isPrevious,
18        public bool $isNext,
19    ) {
20        if (!self::validateUrl($url)) {
21            throw new InvalidArgumentException();
22        }
23    }
24
25    public static function forPrevious(?string $url): self
26    {
27        return new self($url, "previous", false, true, false);
28    }
29
30    public static function forNext(?string $url): self
31    {
32        return new self($url, "next", false, false, true);
33    }
34
35    public static function forNumber(?string $url, int $pageNumber, bool $isCurrent): self
36    {
37        return new self($url, strval($pageNumber), $isCurrent, false, false);
38    }
39
40    private static function validateUrl(?string $url): bool
41    {
42        if ($url === null) {
43            return true;
44        }
45        if ($url === "") {
46            return false;
47        }
48        $baseUrl = new Url("http://base.url"); // allow relative URLs
49        try {
50            $parsedUrl = new Url($url, $baseUrl);
51        } catch (InvalidUrlException) {
52            return false;
53        }
54        return in_array($parsedUrl->getScheme(), ["http", "https"], true);
55    }
56}