Completed
Push — master ( b25a31...347863 )
by Jakub
01:41
created

DataProvider   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 75%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 23
c 1
b 0
f 1
dl 0
loc 38
ccs 15
cts 20
cp 0.75
rs 10
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A getData() 0 23 6
1
<?php
2
declare(strict_types=1);
3
4
namespace MyTester;
5
6
use MyTester\Annotations\Reader;
7
use ReflectionMethod;
8
9
/**
10
 * DataProvider
11
 *
12
 * @author Jakub Konečný
13
 * @internal
14
 */
15
final class DataProvider {
16
  use \Nette\SmartObject;
17
18
  public const ANNOTATION_NAME = "data";
19
  public const PROVIDER_ANNOTATION_NAME = "dataProvider";
20
21
  private Reader $annotationsReader;
22
23 1
  public function __construct(Reader $annotationsReader) {
24 1
    $this->annotationsReader = $annotationsReader;
25 1
  }
26
27
  /**
28
   * @throws InvalidDataProviderException
29
   */
30 1
  public function getData(object $class, string $method): array {
31 1
    $reflection = new ReflectionMethod($class, $method);
32 1
    if($reflection->getNumberOfParameters() < 1) {
33 1
      return [];
34
    }
35 1
    $dataProvider = $this->annotationsReader->getAnnotation(static::PROVIDER_ANNOTATION_NAME, $class, $method);
36 1
    if(is_string($dataProvider)) {
37 1
      $className = $reflection->getDeclaringClass()->getName();
38
      try {
39 1
        $reflection = new ReflectionMethod($class, $dataProvider);
40 1
        if(!$reflection->isPublic()) {
41
          throw new InvalidDataProviderException("Method $className::$dataProvider is not public.");
42
        }
43 1
        $result = call_user_func([$class, $dataProvider]);
44 1
        if(!is_array($result)) {
45
          throw new InvalidDataProviderException("Method $className::$dataProvider has to return an array.");
46
        }
47 1
        return $result;
48
      } catch(\ReflectionException $e) {
49
        throw new InvalidDataProviderException("Method $className::$dataProvider does not exist.", 0, $e);
50
      }
51
    }
52
    return [];
53
  }
54
}
55
?>