Passed
Push — master ( de3d61...be839c )
by Alec
13:42 queued 13s
created

WidthMeasurer   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 27
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A measureWidth() 0 3 1
A __construct() 0 4 1
A assert() 0 13 3
1
<?php
2
3
declare(strict_types=1);
4
5
6
namespace AlecRabbit\Spinner\Core;
7
8
use AlecRabbit\Spinner\Core\Contract\IWidthMeasurer;
9
use AlecRabbit\Spinner\Exception\InvalidArgumentException;
10
use Closure;
11
use ReflectionFunction;
12
13
final class WidthMeasurer implements IWidthMeasurer
14
{
15
    public function __construct(
16
        protected Closure $measureFunction,
17
    ) {
18
        self::assert($this->measureFunction);
19
    }
20
21
    private static function assert(Closure $measureFunction): void
22
    {
23
        $reflection = new ReflectionFunction($measureFunction);
24
        $returnType = $reflection->getReturnType()?->getName();
0 ignored issues
show
Bug introduced by
The method getName() does not exist on ReflectionType. It seems like you code against a sub-type of ReflectionType such as ReflectionNamedType. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

24
        $returnType = $reflection->getReturnType()?->/** @scrutinizer ignore-call */ getName();
Loading history...
25
        $parameterType = $reflection->getParameters()[0]->getType()?->getName();
26
27
        if ($parameterType === 'string' && $returnType === 'int') {
28
            return;
29
        }
30
31
        throw new InvalidArgumentException(
32
            'Invalid measure function signature.'
33
            . ' Signature expected to be: "function(string $string): int { //... }".'
34
        );
35
    }
36
37
    public function measureWidth(string $string): int
38
    {
39
        return (int)($this->measureFunction)($string);
40
    }
41
}
42