Completed
Push — master ( 5294dc...c896df )
by T
04:42
created

ClassMethodAnalyzer   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 104
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 100%

Importance

Changes 5
Bugs 0 Features 2
Metric Value
wmc 12
c 5
b 0
f 2
lcom 1
cbo 7
dl 0
loc 104
ccs 55
cts 55
cp 1
rs 10

2 Methods

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