Lines 100.00% 12 / 12
Functions and Methods 100.00% 7 / 7
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
PhpType 100.00% 12 / 12 100.00% 7 / 7 11 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 fromNative 100.00% 1 / 1 100.00% 1 / 1 1
 mixed 100.00% 1 / 1 100.00% 1 / 1 1
 listOf 100.00% 1 / 1 100.00% 1 / 1 1
 nullable 100.00% 6 / 6 100.00% 1 / 1 5
 isPlain 100.00% 1 / 1 100.00% 1 / 1 1
 needsDocblock 100.00% 1 / 1 100.00% 1 / 1 1
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Codegen\Php;
6
7final readonly class PhpType
8{
9    private function __construct(
10        public string $native,
11        public string $docblock,
12    ) {}
13
14    public static function fromNative(string $native, ?string $docblock = null): self
15    {
16        return new self($native, $docblock ?? $native);
17    }
18
19    public static function mixed(): self
20    {
21        return new self('mixed', 'mixed');
22    }
23
24    public function listOf(): self
25    {
26        return new self('array', 'list<' . $this->docblock . '>');
27    }
28
29    public function nullable(): self
30    {
31        if ($this->native === 'mixed') {
32            return $this;
33        }
34
35        return new self(
36            str_contains($this->native, '|') ? $this->native . '|null' : '?' . $this->native,
37            $this->docblock === $this->native && self::isPlain($this->docblock) ? '?' . $this->docblock : $this->docblock . '|null',
38        );
39    }
40
41    private static function isPlain(string $type): bool
42    {
43        return preg_match('/\\A[A-Za-z_][A-Za-z0-9_]*\\z/', $type) === 1;
44    }
45
46    public function needsDocblock(): bool
47    {
48        return $this->docblock !== $this->native;
49    }
50}