Completed
Pull Request — master (#99)
by
unknown
01:44
created

ClassMethodAnalyzer::analyze()   F

Complexity

Conditions 13
Paths 288

Size

Total Lines 108
Code Lines 67

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 57
CRAP Score 13

Importance

Changes 0
Metric Value
dl 0
loc 108
ccs 57
cts 57
cp 1
rs 3.7737
c 0
b 0
f 0
cc 13
eloc 67
nc 288
nop 2
crap 13

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\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\ClassMethodRenamedCaseOnly;
21
use PHPSemVerChecker\Report\Report;
22
23
class ClassMethodAnalyzer {
24
	protected $context;
25
	protected $fileBefore;
26
	protected $fileAfter;
27
28
	/**
29
	 * @param string $context
30
	 * @param string $fileBefore
31
	 * @param string $fileAfter
32
	 */
33 101
	public function __construct($context, $fileBefore = null, $fileAfter = null)
34
	{
35 101
		$this->context = $context;
36 101
		$this->fileBefore = $fileBefore;
37 101
		$this->fileAfter = $fileAfter;
38 101
	}
39
40 101
	public function analyze(Stmt $contextBefore, Stmt $contextAfter)
41
	{
42 101
		$report = new Report();
43
44 101
		$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...
45 101
		$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...
46
47 101
		$methodsBeforeKeyed = [];
48 101
		foreach ($methodsBefore as $method) {
49 91
			$methodsBeforeKeyed[strtolower($method->name)] = $method;
50
		}
51
52 101
		$methodsAfterKeyed = [];
53 101
		foreach ($methodsAfter as $method) {
54 91
			$methodsAfterKeyed[strtolower($method->name)] = $method;
55
		}
56
57 101
		$methodNamesBefore = array_keys($methodsBeforeKeyed);
58 101
		$methodNamesAfter = array_keys($methodsAfterKeyed);
59 101
		$methodsAdded = array_diff($methodNamesAfter, $methodNamesBefore);
60 101
		$methodsRemoved = array_diff($methodNamesBefore, $methodNamesAfter);
61 101
		$methodsToVerify = array_intersect($methodNamesBefore, $methodNamesAfter);
62
63
		// Here we only care about public methods as they are the only part of the API we care about
64
65
		// Removed methods can either be implemented in parent classes or not exist anymore
66 101
		foreach ($methodsRemoved as $method) {
67 7
			$methodBefore = $methodsBeforeKeyed[$method];
68 7
			$data = new ClassMethodRemoved($this->context, $this->fileBefore, $contextBefore, $methodBefore);
69 7
			$report->add($this->context, $data);
70
		}
71
72 101
		foreach ($methodsToVerify as $method) {
73
			/** @var \PhpParser\Node\Stmt\ClassMethod $methodBefore */
74 84
			$methodBefore = $methodsBeforeKeyed[strtolower($method)];
75
			/** @var \PhpParser\Node\Stmt\ClassMethod $methodAfter */
76 84
			$methodAfter = $methodsAfterKeyed[strtolower($method)];
77
78
			// Leave non-strict comparison here
79 84
			if ($methodBefore != $methodAfter) {
80
81
				// Detect method renamed case only.
82
				if(
83 63
					$methodBefore->name !== $methodAfter->name
84 63
					 && strtolower($methodBefore->name) === strtolower($methodAfter->name)
85
				) {
86 1
					$report->add($this->context, new ClassMethodRenamedCaseOnly($this->context, $this->fileAfter, $contextAfter, $methodAfter));
87
				}
88
89 63
				$signatureResult = Signature::analyze($methodBefore->getParams(), $methodAfter->getParams());
90
91
				$changes = [
92 63
					'parameter_added' => ClassMethodParameterAdded::class,
93
					'parameter_removed' => ClassMethodParameterRemoved::class,
94
					'parameter_renamed' => ClassMethodParameterNameChanged::class,
95
					'parameter_typing_added' => ClassMethodParameterTypingAdded::class,
96
					'parameter_typing_removed' => ClassMethodParameterTypingRemoved::class,
97
					'parameter_default_added' => ClassMethodParameterDefaultAdded::class,
98
					'parameter_default_removed' => ClassMethodParameterDefaultRemoved::class,
99
					'parameter_default_value_changed' => ClassMethodParameterDefaultValueChanged::class,
100
				];
101
102 63
				foreach ($changes as $changeType => $class) {
103 63
					if ( ! $signatureResult[$changeType]) {
104 63
						continue;
105
					}
106 56
					if (is_a($class, ClassMethodOperationUnary::class, true)) {
107 42
						$data = new $class($this->context, $this->fileAfter, $contextAfter, $methodAfter);
108
					} else {
109 14
						$data = new $class(
110 14
							$this->context,
111 14
							$this->fileBefore,
112 14
							$contextBefore,
113 14
							$methodBefore,
114 14
							$this->fileAfter,
115 14
							$contextAfter,
116 14
							$methodAfter
117
						);
118
					}
119 56
					$report->add($this->context, $data);
120
				}
121
122
				// Difference in source code
123
				// Cast to array because interfaces do not have stmts (= null)
124 63
				if (!Implementation::isSame((array)$methodBefore->stmts, (array)$methodAfter->stmts)) {
125 6
					$data = new ClassMethodImplementationChanged(
126 6
						$this->context,
127 6
						$this->fileBefore,
128 6
						$contextBefore,
129 6
						$methodBefore,
130 6
						$this->fileAfter,
131 6
						$contextAfter,
132 6
						$methodAfter
133
					);
134 84
					$report->add($this->context, $data);
135
				}
136
			}
137
		}
138
139
		// Added methods implies MINOR BUMP
140 101
		foreach ($methodsAdded as $method) {
141 7
			$methodAfter = $methodsAfterKeyed[strtolower($method)];
142 7
			$data = new ClassMethodAdded($this->context, $this->fileAfter, $contextAfter, $methodAfter);
143 7
			$report->add($this->context, $data);
144
		}
145
146 101
		return $report;
147
	}
148
}
149