Completed
Pull Request — master (#99)
by
unknown
02:17
created

ClassMethodAnalyzer   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 149
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 8
dl 0
loc 149
ccs 89
cts 89
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
F analyze() 0 117 12
1
<?php
2
3
namespace PHPSemVerChecker\Analyzer;
4
5
use PhpParser\Node\Stmt;
6
use PHPSemVerChecker\Comparator\Implementation;
7
use PHPSemVerChecker\Comparator\Signature;
8
use PHPSemVerChecker\Operation\ClassMethodAdded;
9
use PHPSemVerChecker\Operation\ClassMethodImplementationChanged;
10
use PHPSemVerChecker\Operation\ClassMethodOperationUnary;
11
use PHPSemVerChecker\Operation\ClassMethodParameterAdded;
12
use PHPSemVerChecker\Operation\ClassMethodParameterDefaultAdded;
13
use PHPSemVerChecker\Operation\ClassMethodParameterDefaultRemoved;
14
use PHPSemVerChecker\Operation\ClassMethodParameterDefaultValueChanged;
15
use PHPSemVerChecker\Operation\ClassMethodParameterNameChanged;
16
use PHPSemVerChecker\Operation\ClassMethodParameterRemoved;
17
use PHPSemVerChecker\Operation\ClassMethodParameterTypingAdded;
18
use PHPSemVerChecker\Operation\ClassMethodParameterTypingRemoved;
19
use PHPSemVerChecker\Operation\ClassMethodRemoved;
20
use PHPSemVerChecker\Operation\ClassMethodCaseChanged;
21
use PHPSemVerChecker\Report\Report;
22
23
class ClassMethodAnalyzer {
24
	/**
25
	 * @var string
26
	 */
27
	protected $context;
28
	/**
29
	 * @var null|string
30
	 */
31
	protected $fileBefore;
32
	/**
33
	 * @var null|string
34
	 */
35
	protected $fileAfter;
36
37
	/**
38
	 * @param string $context
39
	 * @param string $fileBefore
40
	 * @param string $fileAfter
41
	 */
42 106
	public function __construct($context, $fileBefore = null, $fileAfter = null)
43
	{
44 106
		$this->context = $context;
45 106
		$this->fileBefore = $fileBefore;
46 106
		$this->fileAfter = $fileAfter;
47 106
	}
48
49
	/**
50
	 * @param \PhpParser\Node\Stmt $contextBefore
51
	 * @param \PhpParser\Node\Stmt $contextAfter
52
	 * @return \PHPSemVerChecker\Report\Report
53
	 */
54 106
	public function analyze(Stmt $contextBefore, Stmt $contextAfter)
55
	{
56 106
		$report = new Report();
57
58 106
		$methodsBefore = $contextBefore->getMethods();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class PhpParser\Node\Stmt as the method getMethods() does only exist in the following sub-classes of PhpParser\Node\Stmt: PhpParser\Node\Stmt\ClassLike, PhpParser\Node\Stmt\Class_, PhpParser\Node\Stmt\Interface_, PhpParser\Node\Stmt\Trait_. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
59 106
		$methodsAfter = $contextAfter->getMethods();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class PhpParser\Node\Stmt as the method getMethods() does only exist in the following sub-classes of PhpParser\Node\Stmt: PhpParser\Node\Stmt\ClassLike, PhpParser\Node\Stmt\Class_, PhpParser\Node\Stmt\Interface_, PhpParser\Node\Stmt\Trait_. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
60
61 106
		$methodsBeforeKeyed = [];
62 106
		foreach ($methodsBefore as $method) {
63 96
			$methodsBeforeKeyed[strtolower($method->name)] = $method;
64 106
		}
65
66 106
		$methodsAfterKeyed = [];
67 106
		foreach ($methodsAfter as $method) {
68 96
			$methodsAfterKeyed[strtolower($method->name)] = $method;
69 106
		}
70
71 106
		$methodNamesBefore = array_keys($methodsBeforeKeyed);
72 106
		$methodNamesAfter = array_keys($methodsAfterKeyed);
73 106
		$methodsAdded = array_diff($methodNamesAfter, $methodNamesBefore);
74 106
		$methodsRemoved = array_diff($methodNamesBefore, $methodNamesAfter);
75 106
		$methodsToVerify = array_intersect($methodNamesBefore, $methodNamesAfter);
76
77
		// Here we only care about public methods as they are the only part of the API we care about
78
79
		// Removed methods can either be implemented in parent classes or not exist anymore
80 106
		foreach ($methodsRemoved as $method) {
81 7
			$methodBefore = $methodsBeforeKeyed[$method];
82 7
			$data = new ClassMethodRemoved($this->context, $this->fileBefore, $contextBefore, $methodBefore);
83 7
			$report->add($this->context, $data);
84 106
		}
85
86 106
		foreach ($methodsToVerify as $method) {
87
			/** @var \PhpParser\Node\Stmt\ClassMethod $methodBefore */
88 89
			$methodBefore = $methodsBeforeKeyed[strtolower($method)];
89
			/** @var \PhpParser\Node\Stmt\ClassMethod $methodAfter */
90 89
			$methodAfter = $methodsAfterKeyed[strtolower($method)];
91
92
			// Leave non-strict comparison here
93 89
			if ($methodBefore != $methodAfter) {
94
95
				// Detect method case changed.
96
				// If we entered this section then the normalized names (lowercase) were equal.
97 68
				if ($methodBefore->name !== $methodAfter->name) {
98 6
					$report->add(
99 6
						$this->context,
100 6
						new ClassMethodCaseChanged(
101 6
							$this->context,
102 6
							$this->fileBefore,
103 6
							$contextAfter,
104 6
							$methodBefore,
105 6
							$this->fileAfter,
106 6
							$contextAfter,
107
							$methodAfter
108 6
						)
109 6
					);
110 6
				}
111
112 68
				$signatureResult = Signature::analyze($methodBefore->getParams(), $methodAfter->getParams());
113
114
				$changes = [
115 68
					'parameter_added' => ClassMethodParameterAdded::class,
116 68
					'parameter_removed' => ClassMethodParameterRemoved::class,
117 68
					'parameter_renamed' => ClassMethodParameterNameChanged::class,
118 68
					'parameter_typing_added' => ClassMethodParameterTypingAdded::class,
119 68
					'parameter_typing_removed' => ClassMethodParameterTypingRemoved::class,
120 68
					'parameter_default_added' => ClassMethodParameterDefaultAdded::class,
121 68
					'parameter_default_removed' => ClassMethodParameterDefaultRemoved::class,
122 68
					'parameter_default_value_changed' => ClassMethodParameterDefaultValueChanged::class,
123 68
				];
124
125 68
				foreach ($changes as $changeType => $class) {
126 68
					if ( ! $signatureResult[$changeType]) {
127 68
						continue;
128
					}
129 56
					if (is_a($class, ClassMethodOperationUnary::class, true)) {
130 42
						$data = new $class($this->context, $this->fileAfter, $contextAfter, $methodAfter);
131 42
					} else {
132 14
						$data = new $class(
133 14
							$this->context,
134 14
							$this->fileBefore,
135 14
							$contextBefore,
136 14
							$methodBefore,
137 14
							$this->fileAfter,
138 14
							$contextAfter,
139
							$methodAfter
140 14
						);
141
					}
142 56
					$report->add($this->context, $data);
143 68
				}
144
145
				// Difference in source code
146
				// Cast to array because interfaces do not have stmts (= null)
147 68
				if (!Implementation::isSame((array)$methodBefore->stmts, (array)$methodAfter->stmts)) {
148 6
					$data = new ClassMethodImplementationChanged(
149 6
						$this->context,
150 6
						$this->fileBefore,
151 6
						$contextBefore,
152 6
						$methodBefore,
153 6
						$this->fileAfter,
154 6
						$contextAfter,
155
						$methodAfter
156 6
					);
157 6
					$report->add($this->context, $data);
158 6
				}
159 68
			}
160 106
		}
161
162
		// Added methods implies MINOR BUMP
163 106
		foreach ($methodsAdded as $method) {
164 7
			$methodAfter = $methodsAfterKeyed[strtolower($method)];
165 7
			$data = new ClassMethodAdded($this->context, $this->fileAfter, $contextAfter, $methodAfter);
166 7
			$report->add($this->context, $data);
167 106
		}
168
169 106
		return $report;
170
	}
171
}
172