Completed
Push — 6-php_attributes ( 62d696 )
by Jakub
02:25
created

PhpAttributesEngine::isAvailable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 1
c 1
b 0
f 1
nc 1
nop 0
dl 0
loc 2
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace MyTester\Annotations;
5
6
use Nette\Utils\Strings;
7
use ReflectionMethod;
8
9
final class PhpAttributesEngine implements \MyTester\IAnnotationsReaderEngine {
10
  public function hasAnnotation(string $name, $class, string $method = null): bool {
11
    if(!$this->isAvailable()) {
12
      return false;
13
    }
14
    $attributeClassName = $this->getClassName($name);
15
    if($method !== null) {
16
      $reflection = new ReflectionMethod(is_object($class) ? get_class($class) : $class, $method);
17
    } else {
18
      $reflection = new \ReflectionClass(is_object($class) ? get_class($class) : $class);
19
    }
20
    return count($reflection->getAttributes($attributeClassName)) > 0;
1 ignored issue
show
Bug introduced by
The method getAttributes() does not exist on ReflectionClass. It seems like you code against a sub-type of ReflectionClass such as Nette\Reflection\ClassType. ( Ignorable by Annotation )

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

20
    return count($reflection->/** @scrutinizer ignore-call */ getAttributes($attributeClassName)) > 0;
Loading history...
introduced by
The method getAttributes() does not exist on ReflectionMethod. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

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

20
    return count($reflection->/** @scrutinizer ignore-call */ getAttributes($attributeClassName)) > 0;
Loading history...
21
  }
22
23
  public function getAnnotation(string $name, $class, string $method = null) {
24
    if(!$this->isAvailable()) {
25
      return null;
26
    }
27
    $attributeClassName = $this->getClassName($name);
28
    if($method !== null) {
29
      $reflection = new ReflectionMethod(is_object($class) ? get_class($class) : $class, $method);
30
    } else {
31
      $reflection = new \ReflectionClass(is_object($class) ? get_class($class) : $class);
32
    }
33
    $attributes = $reflection->getAttributes($attributeClassName);
34
    if(count($attributes) === 0) {
35
      return null;
36
    }
37
    return $attributes[0];
38
  }
39
40
  private function isAvailable(): bool {
41
    return version_compare(PHP_VERSION, "7.5.0", ">");
42
  }
43
44
  private function getClassName(string $baseName): string {
45
    return "MyTester\\Annotations\Attributes\\" . Strings::firstUpper($baseName);
46
  }
47
}
48
?>