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

DataProvider::getData()   A

Complexity

Conditions 6
Paths 9

Size

Total Lines 23
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6.9157

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 6
eloc 17
c 1
b 0
f 1
nc 9
nop 2
dl 0
loc 23
ccs 12
cts 17
cp 0.7059
crap 6.9157
rs 9.0777
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
?>