GroupManager::groupsForTest()   F
last analyzed

Complexity

Conditions 16
Paths 648

Size

Total Lines 45

Duplication

Lines 6
Ratio 13.33 %

Importance

Changes 0
Metric Value
cc 16
nc 648
nop 1
dl 6
loc 45
rs 1.8888
c 0
b 0
f 0

How to fix   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
namespace Codeception\Lib;
3
4
use Codeception\Configuration;
5
use Codeception\Test\Interfaces\Reported;
6
use Codeception\Test\Descriptor;
7
use Codeception\TestInterface;
8
use Symfony\Component\Finder\Finder;
9
use Symfony\Component\Finder\SplFileInfo;
10
11
/**
12
 * Loads information for groups from external sources (config, filesystem)
13
 */
14
class GroupManager
15
{
16
    protected $configuredGroups;
17
    protected $testsInGroups = [];
18
19
    public function __construct(array $groups)
20
    {
21
        $this->configuredGroups = $groups;
22
        $this->loadGroupsByPattern();
23
        $this->loadConfiguredGroupSettings();
24
    }
25
26
    /**
27
     * proceeds group names with asterisk:
28
     *
29
     * ```
30
     * "tests/_log/g_*" => [
31
     *      "tests/_log/group_1",
32
     *      "tests/_log/group_2",
33
     *      "tests/_log/group_3",
34
     * ]
35
     * ```
36
     */
37
    protected function loadGroupsByPattern()
38
    {
39
        foreach ($this->configuredGroups as $group => $pattern) {
40
            if (strpos($group, '*') === false) {
41
                continue;
42
            }
43
            $files = Finder::create()->files()
44
                ->name(basename($pattern))
45
                ->sortByName()
46
                ->in(Configuration::projectDir().dirname($pattern));
47
48
            $i = 1;
49
            foreach ($files as $file) {
50
                /** @var SplFileInfo $file * */
51
                $this->configuredGroups[str_replace('*', $i, $group)] = dirname($pattern).DIRECTORY_SEPARATOR.$file->getRelativePathname();
52
                $i++;
53
            }
54
            unset($this->configuredGroups[$group]);
55
        }
56
    }
57
58
    protected function loadConfiguredGroupSettings()
59
    {
60
        foreach ($this->configuredGroups as $group => $tests) {
61
            $this->testsInGroups[$group] = [];
62
            if (is_array($tests)) {
63
                foreach ($tests as $test) {
64
                    $file = str_replace(['/', '\\'], [DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR], $test);
65
                    $this->testsInGroups[$group][] = Configuration::projectDir() . $file;
66
                }
67
            } elseif (is_file(Configuration::projectDir() . $tests)) {
68
                $handle = @fopen(Configuration::projectDir() . $tests, "r");
69
                if ($handle) {
70
                    while (($test = fgets($handle, 4096)) !== false) {
71
                        // if the current line is blank then we need to move to the next line
72
                        // otherwise the current codeception directory becomes part of the group
73
                        // which causes every single test to run
74
                        if (trim($test) === '') {
75
                            continue;
76
                        }
77
78
                        $file = trim(Configuration::projectDir() . $test);
79
                        $file = str_replace(['/', '\\'], [DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR], $file);
80
                        $this->testsInGroups[$group][] = $file;
81
                    }
82
                    fclose($handle);
83
                }
84
            }
85
        }
86
    }
87
88
    public function groupsForTest(\PHPUnit\Framework\Test $test)
89
    {
90
        $groups = [];
91
        $filename = Descriptor::getTestFileName($test);
0 ignored issues
show
Documentation introduced by
$test is of type object<PHPUnit\Framework\Test>, but the function expects a object<PHPUnit\Framework\SelfDescribing>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
92
        if ($test instanceof TestInterface) {
93
            $groups = $test->getMetadata()->getGroups();
94
        }
95
        if ($test instanceof Reported) {
96
            $info = $test->getReportFields();
97
            if (isset($info['class'])) {
98
                $groups = array_merge($groups, \PHPUnit\Util\Test::getGroups($info['class'], $info['name']));
99
            }
100
            $filename = str_replace(['\\\\', '//'], ['\\', '/'], $info['file']);
101
        }
102
        if ($test instanceof \PHPUnit\Framework\TestCase) {
103
            $groups = array_merge($groups, \PHPUnit\Util\Test::getGroups(get_class($test), $test->getName(false)));
104
        }
105
        if ($test instanceof \PHPUnit\Framework\TestSuite\DataProvider) {
106
            $firstTest = $test->testAt(0);
107
            if ($firstTest != false && $firstTest instanceof TestInterface) {
108
                $groups = array_merge($groups, $firstTest->getMetadata()->getGroups());
109
                $filename = Descriptor::getTestFileName($firstTest);
0 ignored issues
show
Documentation introduced by
$firstTest is of type object<Codeception\TestInterface>, but the function expects a object<PHPUnit\Framework\SelfDescribing>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
110
            }
111
        }
112
113
        foreach ($this->testsInGroups as $group => $tests) {
114
            foreach ($tests as $testPattern) {
115
                if ($filename == $testPattern) {
116
                    $groups[] = $group;
117
                }
118 View Code Duplication
                if (strpos($filename . ':' . $test->getName(false), $testPattern) === 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Bug introduced by
It seems like you code against a concrete implementation and not the interface PHPUnit\Framework\Test as the method getName() does only exist in the following implementations of said interface: AbstractTest, AssertionExampleTest, BankAccountTest, BankAccountWithCustomExtensionTest, BeforeAndAfterTest, BeforeClassAndAfterClassTest, BeforeClassWithOnlyDataProviderTest, ChangeCurrentWorkingDirectoryTest, ClonedDependencyTest, Codeception\Suite, Codeception\TestCase\Test, Codeception\Test\Cept, Codeception\Test\Cest, Codeception\Test\Gherkin, Codeception\Test\Test, Codeception\Test\Unit, ConcreteTest, ConcreteWithMyCustomExtensionTest, ConsecutiveParametersTest, CoverageClassExtendedTest, CoverageClassTest, CoverageCoversOverridesCoversNothingTest, CoverageFunctionParenthesesTest, CoverageFunctionParenthesesWhitespaceTest, CoverageFunctionTest, CoverageMethodOneLineAnnotationTest, CoverageMethodParenthesesTest, CoverageMethodParenthesesWhitespaceTest, CoverageMethodTest, CoverageNamespacedFunctionTest, CoverageNoneTest, CoverageNotPrivateTest, CoverageNotProtectedTest, CoverageNotPublicTest, CoverageNothingTest, CoveragePrivateTest, CoverageProtectedTest, CoveragePublicTest, DataProviderDebugTest, DataProviderDependencyTest, DataProviderFilterTest, DataProviderIncompleteTest, DataProviderSkippedTest, DataProviderTest, DataProviderTestDoxTest, DependencyFailureTest, DependencySuccessTest, DoNoAssertionTestCase, DoesNotPerformAssertions...erformingAssertionsTest, DummyBarTest, DummyFooTest, EmptyTestCaseTest, ExceptionInAssertPostConditionsTest, ExceptionInAssertPreConditionsTest, ExceptionInSetUpTest, ExceptionInTearDownTest, ExceptionInTest, ExceptionInTestDetectedInTeardown, ExceptionStackTest, ExceptionTest, Failure, FailureTest, FatalTest, Foo\DataProviderIssue2833\FirstTest, Foo\DataProviderIssue2833\SecondTest, Foo\DataProviderIssue2859\TestWithDataProviderTest, Foo\DataProviderIssue2922\FirstTest, Foo\DataProviderIssue2922\SecondHelloWorldTest, Foo_Bar_Issue684Test, Framework\Constraint\LogicalXorTest, GeneratorTest, IgnoreCodeCoverageClassTest, IncompleteTest, InheritanceA, InheritanceB, InheritedTestCase, IniTest, InvocationMockerTest, IsolationTest, Issue1021Test, Issue1149Test, Issue1216Test, Issue1265Test, Issue1330Test, Issue1335Test, Issue1337Test, Issue1348Test, Issue1351Test, Issue1374Test, Issue1437Test, Issue1468Test, Issue1471Test, Issue1472Test, Issue1570Test, Issue2137Test, Issue2145Test, Issue2158Test, Issue2366Test, Issue2380Test, Issue2382Test, Issue2435Test, Issue244Test, Issue2591_SeparateClassPreserveTest, Issue2591_SeparateFunctionNoPreserveTest, Issue2591_SeparateFunctionPreserveTest, Issue2725\BeforeAfterClassPidTest, Issue2731Test, Issue2811Test, Issue2830Test, Issue2972\Issue2972Test, Issue3093Test, Issue3107\Issue3107Test, Issue322Test, Issue433Test, Issue445Test, Issue498Test, Issue503Test, Issue523Test, Issue578Test, Issue581Test, Issue74Test, Issue765Test, Issue797Test, MockBuilderTest, MockObjectTest, MultiDependencyTest, MultipleDataProviderTest, My\Space\ExceptionNamespaceTest, NamespaceCoverageClassExtendedTest, NamespaceCoverageClassTest, NamespaceCoverageCoversClassPublicTest, NamespaceCoverageCoversClassTest, NamespaceCoverageMethodTest, NamespaceCoverageNotPrivateTest, NamespaceCoverageNotProtectedTest, NamespaceCoverageNotPublicTest, NamespaceCoveragePrivateTest, NamespaceCoverageProtectedTest, NamespaceCoveragePublicTest, NoArgTestCaseTest, NoTestCases, NotExistingCoveredElementTest, NotPublicTestCase, NotVoidTestCase, NothingTest, ObjectInvocationTest, OneTest, OneTestCase, OutputTestCase, OverrideTestCase, PHPUnit\Framework\AssertTest, PHPUnit\Framework\ConstraintTest, PHPUnit\Framework\Constraint\ArrayHasKeyTest, PHPUnit\Framework\Constraint\ArraySubsetTest, PHPUnit\Framework\Constraint\AttributeTest, PHPUnit\Framework\Constraint\CallbackTest, PHPUnit\Framework\Constraint\ClassHasAttributeTest, PHPUnit\Framework\Constr...sHasStaticAttributeTest, PHPUnit\Framework\Constraint\ConstraintTestCase, PHPUnit\Framework\Constraint\CountTest, PHPUnit\Framework\Constraint\DirectoryExistsTest, PHPUnit\Framework\Constr...eptionMessageRegExpTest, PHPUnit\Framework\Constraint\ExceptionMessageTest, PHPUnit\Framework\Constraint\FileExistsTest, PHPUnit\Framework\Constraint\GreaterThanTest, PHPUnit\Framework\Constraint\IsEmptyTest, PHPUnit\Framework\Constraint\IsEqualTest, PHPUnit\Framework\Constraint\IsIdenticalTest, PHPUnit\Framework\Constraint\IsInstanceOfTest, PHPUnit\Framework\Constraint\IsJsonTest, PHPUnit\Framework\Constraint\IsNullTest, PHPUnit\Framework\Constraint\IsReadableTest, PHPUnit\Framework\Constraint\IsTypeTest, PHPUnit\Framework\Constraint\IsWritableTest, PHPUnit\Framework\Constr...rrorMessageProviderTest, PHPUnit\Framework\Constraint\JsonMatchesTest, PHPUnit\Framework\Constraint\LessThanTest, PHPUnit\Framework\Constraint\LogicalAndTest, PHPUnit\Framework\Constraint\LogicalOrTest, PHPUnit\Framework\Constr...\ObjectHasAttributeTest, PHPUnit\Framework\Constraint\RegularExpressionTest, PHPUnit\Framework\Constraint\SameSizeTest, PHPUnit\Framework\Constraint\StringContainsTest, PHPUnit\Framework\Constraint\StringEndsWithTest, PHPUnit\Framework\Constr...esFormatDescriptionTest, PHPUnit\Framework\Constraint\StringStartsWithTest, PHPUnit\Framework\Constr...TraversableContainsTest, PHPUnit\Framework\DataProviderTestSuite, PHPUnit\Framework\ExceptionWrapperTest, PHPUnit\Framework\IncompleteTestCase, PHPUnit\Framework\SkippedTestCase, PHPUnit\Framework\TestCase, PHPUnit\Framework\TestCaseTest, PHPUnit\Framework\TestFailureTest, PHPUnit\Framework\TestImplementorTest, PHPUnit\Framework\TestListenerTest, PHPUnit\Framework\TestSuite, PHPUnit\Framework\TestSuiteSorterTest, PHPUnit\Framework\TestSuiteTest, PHPUnit\Framework\WarningTestCase, PHPUnit\Runner\PhptTestCase, PHPUnit\Runner\PhptTestCaseTest, PHPUnit\Test\HookTest, PHPUnit\Util\ConfigurationGeneratorTest, PHPUnit\Util\ConfigurationTest, PHPUnit\Util\GetoptTest, PHPUnit\Util\GlobalStateTest, PHPUnit\Util\JsonTest, PHPUnit\Util\PHP\AbstractPhpProcessTest, PHPUnit\Util\RegularExpressionTest, PHPUnit\Util\TestDox\CliTestDoxPrinterTest, PHPUnit\Util\TestDox\NamePrettifierTest, PHPUnit\Util\TestTest, PHPUnit\Util\XmlTest, ProxyObjectTest, RequirementsClassBeforeClassHookTest, RequirementsTest, SeparateClassRunMethodInNewProcessTest, StackTest, StaticInvocationTest, StopsOnWarningTest, StubTest, StubTraitTest, Success, TemplateMethodsTest, Test, TestAutoreferenced, TestDoxGroupTest, TestError, TestIncomplete, TestSkipped, TestWithTest, Test\Issue3156Test, ThrowExceptionTestCase, ThrowNoExceptionTestCase, TwoTest, WasRun, vendor\project\StatusTest.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
119
                    $groups[] = $group;
120
                }
121
                if ($test instanceof \PHPUnit\Framework\TestSuite\DataProvider) {
122
                    $firstTest = $test->testAt(0);
123
                    if ($firstTest != false && $firstTest instanceof TestInterface) {
124 View Code Duplication
                        if (strpos($filename . ':' . $firstTest->getName(false), $testPattern) === 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
125
                            $groups[] = $group;
126
                        }
127
                    }
128
                }
129
            }
130
        }
131
        return array_unique($groups);
132
    }
133
}
134