Completed
Push — master ( 1cdbe4...17a825 )
by T
02:03
created

ClassMethodAnalyzer::analyze()   F

Complexity

Conditions 12
Paths 288

Size

Total Lines 116
Code Lines 74

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 65
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 116
ccs 65
cts 65
cp 1
rs 3.7956
c 0
b 0
f 0
cc 12
eloc 74
nc 288
nop 2
crap 12

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\ClassMethodCaseChanged;
10
use PHPSemVerChecker\Operation\ClassMethodImplementationChanged;
11
use PHPSemVerChecker\Operation\ClassMethodOperationUnary;
12
use PHPSemVerChecker\Operation\ClassMethodParameterAdded;
13
use PHPSemVerChecker\Operation\ClassMethodParameterDefaultAdded;
14
use PHPSemVerChecker\Operation\ClassMethodParameterDefaultRemoved;
15
use PHPSemVerChecker\Operation\ClassMethodParameterDefaultValueChanged;
16
use PHPSemVerChecker\Operation\ClassMethodParameterNameChanged;
17
use PHPSemVerChecker\Operation\ClassMethodParameterRemoved;
18
use PHPSemVerChecker\Operation\ClassMethodParameterTypingAdded;
19
use PHPSemVerChecker\Operation\ClassMethodParameterTypingRemoved;
20
use PHPSemVerChecker\Operation\ClassMethodRemoved;
21
use PHPSemVerChecker\Report\Report;
22
23
class ClassMethodAnalyzer
24
{
25
	/**
26
	 * @var string
27
	 */
28
	protected $context;
29
	/**
30
	 * @var null|string
31
	 */
32
	protected $fileBefore;
33
	/**
34
	 * @var null|string
35
	 */
36
	protected $fileAfter;
37
38
	/**
39
	 * @param string $context
40
	 * @param string $fileBefore
41
	 * @param string $fileAfter
42
	 */
43 106
	public function __construct($context, $fileBefore = null, $fileAfter = null)
44
	{
45 106
		$this->context = $context;
46 106
		$this->fileBefore = $fileBefore;
47 106
		$this->fileAfter = $fileAfter;
48 106
	}
49
50
	/**
51
	 * @param \PhpParser\Node\Stmt $contextBefore
52
	 * @param \PhpParser\Node\Stmt $contextAfter
53
	 * @return \PHPSemVerChecker\Report\Report
54
	 */
55 106
	public function analyze(Stmt $contextBefore, Stmt $contextAfter)
56
	{
57 106
		$report = new Report();
58
59 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...
60 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...
61
62 106
		$methodsBeforeKeyed = [];
63 106
		foreach ($methodsBefore as $method) {
64 96
			$methodsBeforeKeyed[strtolower($method->name)] = $method;
65
		}
66
67 106
		$methodsAfterKeyed = [];
68 106
		foreach ($methodsAfter as $method) {
69 96
			$methodsAfterKeyed[strtolower($method->name)] = $method;
70
		}
71
72 106
		$methodNamesBefore = array_keys($methodsBeforeKeyed);
73 106
		$methodNamesAfter = array_keys($methodsAfterKeyed);
74 106
		$methodsAdded = array_diff($methodNamesAfter, $methodNamesBefore);
75 106
		$methodsRemoved = array_diff($methodNamesBefore, $methodNamesAfter);
76 106
		$methodsToVerify = array_intersect($methodNamesBefore, $methodNamesAfter);
77
78
		// Here we only care about public methods as they are the only part of the API we care about
79
80
		// Removed methods can either be implemented in parent classes or not exist anymore
81 106
		foreach ($methodsRemoved as $method) {
82 7
			$methodBefore = $methodsBeforeKeyed[$method];
83 7
			$data = new ClassMethodRemoved($this->context, $this->fileBefore, $contextBefore, $methodBefore);
84 7
			$report->add($this->context, $data);
85
		}
86
87 106
		foreach ($methodsToVerify as $method) {
88
			/** @var \PhpParser\Node\Stmt\ClassMethod $methodBefore */
89 89
			$methodBefore = $methodsBeforeKeyed[strtolower($method)];
90
			/** @var \PhpParser\Node\Stmt\ClassMethod $methodAfter */
91 89
			$methodAfter = $methodsAfterKeyed[strtolower($method)];
92
93
			// Leave non-strict comparison here
94 89
			if ($methodBefore != $methodAfter) {
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 6
							$methodAfter
108
						)
109
					);
110
				}
111
112 68
				$signatureResult = Signature::analyze($methodBefore->getParams(), $methodAfter->getParams());
113
114
				$changes = [
115 68
					'parameter_added'                 => ClassMethodParameterAdded::class,
116
					'parameter_removed'               => ClassMethodParameterRemoved::class,
117
					'parameter_renamed'               => ClassMethodParameterNameChanged::class,
118
					'parameter_typing_added'          => ClassMethodParameterTypingAdded::class,
119
					'parameter_typing_removed'        => ClassMethodParameterTypingRemoved::class,
120
					'parameter_default_added'         => ClassMethodParameterDefaultAdded::class,
121
					'parameter_default_removed'       => ClassMethodParameterDefaultRemoved::class,
122
					'parameter_default_value_changed' => ClassMethodParameterDefaultValueChanged::class,
123
				];
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
					} 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 14
							$methodAfter
140
						);
141
					}
142 56
					$report->add($this->context, $data);
143
				}
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 6
						$methodAfter
156
					);
157 89
					$report->add($this->context, $data);
158
				}
159
			}
160
		}
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
		}
168
169 106
		return $report;
170
	}
171
}
172