testCreateSQLLoggerWithCustomName()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.6333
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace DoctrineORMModuleTest\Service;
4
5
use PHPUnit\Framework\TestCase;
6
use DoctrineORMModule\Service\SQLLoggerCollectorFactory;
7
use Doctrine\DBAL\Logging\DebugStack;
8
use Doctrine\ORM\Configuration as ORMConfiguration;
9
use Laminas\ServiceManager\ServiceManager;
10
11
class SQLLoggerCollectorFactoryTest extends TestCase
12
{
13
    /**
14
     * @var ServiceManager
15
     */
16
    protected $services;
17
18
    /**
19
     * @var SQLLoggerCollectorFactory
20
     */
21
    protected $factory;
22
23
    /**
24
     * {@inheritDoc}
25
     */
26
    public function setUp() : void
27
    {
28
        parent::setUp();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class PHPUnit\Framework\TestCase as the method setUp() does only exist in the following sub-classes of PHPUnit\Framework\TestCase: AbstractIssue3881Test, AbstractTest, AssertionExampleTest, BankAccountTest, BankAccountWithCustomExtensionTest, BeforeAndAfterTest, BeforeClassAndAfterClassTest, BeforeClassWithOnlyDataProviderTest, ChangeCurrentWorkingDirectoryTest, ClonedDependencyTest, ConcreteTest, ConcreteWithMyCustomExtensionTest, ConsecutiveParametersTest, CoverageClassExtendedTest, CoverageClassNothingTest, CoverageClassTest, CoverageClassWithoutAnnotationsTest, CoverageCoversOverridesCoversNothingTest, CoverageFunctionParenthesesTest, CoverageFunctionParenthesesWhitespaceTest, CoverageFunctionTest, CoverageMethodNothingCoversMethod, CoverageMethodNothingTest, CoverageMethodOneLineAnnotationTest, CoverageMethodParenthesesTest, CoverageMethodParenthesesWhitespaceTest, CoverageMethodTest, CoverageNamespacedFunctionTest, CoverageNoneTest, CoverageNotPrivateTest, CoverageNotProtectedTest, CoverageNotPublicTest, CoveragePrivateTest, CoverageProtectedTest, CoveragePublicTest, DataProviderDebugTest, DataProviderDependencyTest, DataProviderFilterTest, DataProviderIncompleteTest, DataProviderSkippedTest, DataProviderTest, DataproviderExecutionOrderTest, DependencyFailureTest, DependencySuccessTest, DoNoAssertionTestCase, DoctrineORMModuleTest\Co...or\MappingCollectorTest, DoctrineORMModuleTest\Co...\SQLLoggerCollectorTest, DoctrineORMModuleTest\Form\AnnotationBuilderTest, DoctrineORMModuleTest\Fo...AnnotationsListenerTest, DoctrineORMModuleTest\Listener\CliConfiguratorTest, DoctrineORMModuleTest\Paginator\AdapterTestIgnore, DoctrineORMModuleTest\Se...onfigurationFactoryTest, DoctrineORMModuleTest\Se...ALConnectionFactoryTest, DoctrineORMModuleTest\Se...tionsCommandFactoryTest, DoctrineORMModuleTest\Se...gerCollectorFactoryTest, DoctrineORMModuleTest\Yuml\MetadataGrapherTest, DoctrineORMModuleTest\Yuml\YumlControllerTest, DoesNotPerformAssertions...erformingAssertionsTest, DummyBarTest, DummyFooTest, DuplicateKeyDataProviderTest, EmptyDataProviderTest, EmptyTestCaseTest, ExceptionInAssertPostConditionsTest, ExceptionInAssertPreConditionsTest, ExceptionInSetUpTest, ExceptionInTearDownAfterClassTest, 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, Issue2085Test, Issue2137Test, Issue2145Test, Issue2158Test, Issue2366Test, Issue2380Test, Issue2382Test, Issue2435Test, Issue2725\BeforeAfterClassPidTest, Issue2731Test, Issue2811Test, Issue2830Test, Issue2972\Issue2972Test, Issue3093Test, Issue322Test, Issue3739\Issue3739Test, Issue3881Test, Issue3889Test, Issue3904Test, Issue3983Test, Issue433Test, Issue445Test, Issue498Test, Issue503Test, Issue578Test, Issue581Test, Issue74Test, Issue765Test, Issue797Test, MockBuilderTest, MockObjectTest, ModifiedConstructorTestCase, MultiDependencyTest, MultipleDataProviderTest, My\Space\ExceptionNamespaceTest, NamespaceCoverageClassExtendedTest, NamespaceCoverageClassTest, NamespaceCoverageCoversClassPublicTest, NamespaceCoverageCoversClassTest, NamespaceCoverageMethodTest, NamespaceCoverageNotPrivateTest, NamespaceCoverageNotProtectedTest, NamespaceCoverageNotPublicTest, NamespaceCoveragePrivateTest, NamespaceCoverageProtectedTest, NamespaceCoveragePublicTest, NoArgTestCaseTest, NoTestCases, NotExistingCoveredElementTest, NotPublicTestCase, NotVoidTestCase, NothingTest, NullTestResultCacheTest, NumericGroupAnnotationTest, OneTest, OneTestCase, OutputTestCase, OverrideTestCase, PHPUnit\Framework\AssertTest, PHPUnit\Framework\ConstraintTest, PHPUnit\Framework\Constraint\ArrayHasKeyTest, PHPUnit\Framework\Constraint\ArraySubsetTest, 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\Constraint\ExceptionCodeTest, PHPUnit\Framework\Constr...eptionMessageRegExpTest, PHPUnit\Framework\Constraint\ExceptionMessageTest, PHPUnit\Framework\Constraint\ExceptionTest, 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\LogicalNotTest, 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\ExceptionTest, PHPUnit\Framework\ExceptionWrapperTest, PHPUnit\Framework\FunctionsTest, PHPUnit\Framework\IncompleteTestCase, PHPUnit\Framework\IncompleteTestCaseTest, PHPUnit\Framework\InvalidArgumentExceptionTest, PHPUnit\Framework\MockOb...\ConfigurableMethodTest, PHPUnit\Framework\MockOb...ConfigurableMethodsTest, PHPUnit\Framework\MockObject\InvocationHandlerTest, PHPUnit\Framework\MockObject\MatcherTest, PHPUnit\Framework\MockObject\MockClassTest, PHPUnit\Framework\MockObject\MockMethodTest, PHPUnit\Framework\MockObject\MockTraitTest, PHPUnit\Framework\SkippedTestCase, PHPUnit\Framework\SkippedTestCaseTest, PHPUnit\Framework\TestBuilderTest, PHPUnit\Framework\TestCaseTest, PHPUnit\Framework\TestFailureTest, PHPUnit\Framework\TestImplementorTest, PHPUnit\Framework\TestListenerTest, PHPUnit\Framework\TestSuiteIteratorTest, PHPUnit\Framework\TestSuiteTest, PHPUnit\Framework\WarningTestCase, PHPUnit\Runner\DefaultTestResultCacheTest, PHPUnit\Runner\Filter\NameFilterIteratorTest, PHPUnit\Runner\PhptTestCaseTest, PHPUnit\Runner\ResultCacheExtensionTest, PHPUnit\Runner\TestSuiteSorterTest, PHPUnit\SelfTest\Basic\SetUpBeforeClassTest, PHPUnit\SelfTest\Basic\SetUpTest, PHPUnit\SelfTest\Basic\StatusTest, PHPUnit\SelfTest\Basic\TearDownAfterClassTest, PHPUnit\StaticAnalysis\TestUsingMocks, PHPUnit\TestFixture\ActualOutputTest, PHPUnit\Test\HookTest, PHPUnit\Util\Annotation\RegistryTest, PHPUnit\Util\ColorTest, PHPUnit\Util\ConfigurationGeneratorTest, PHPUnit\Util\ConfigurationTest, PHPUnit\Util\GetoptTest, PHPUnit\Util\GlobalStateTest, PHPUnit\Util\JsonTest, PHPUnit\Util\PHP\AbstractPhpProcessTest, PHPUnit\Util\RegularExpressionTest, PHPUnit\Util\TestClassTest, PHPUnit\Util\TestDox\CliTestDoxPrinterColorTest, PHPUnit\Util\TestDox\CliTestDoxPrinterTest, PHPUnit\Util\TestDox\NamePrettifierTest, PHPUnit\Util\TestDox\ano...amePrettifierTest.php$0, PHPUnit\Util\TestDox\ano...amePrettifierTest.php$1, PHPUnit\Util\TestDox\ano...amePrettifierTest.php$2, PHPUnit\Util\TestDox\ano...amePrettifierTest.php$3, PHPUnit\Util\XDebugFilterScriptGeneratorTest, PHPUnit\Util\XmlTest, ProxyObjectTest, RequirementsClassBeforeClassHookTest, RequirementsTest, RouterTest, SeparateClassRunMethodInNewProcessTest, SeparateProcessesTest, StackTest, StopOnErrorTestSuite, StopsOnWarningTest, Success, TemplateMethodsTest, Test, Test3194, TestAutoreferenced, TestCaseWithExceptionInHook, TestDoxGroupTest, TestError, TestIncomplete, TestResultCacheTest, TestRisky, TestSkipped, TestWarning, TestWithAnnotations, TestWithDifferentDurations, TestWithDifferentNames, TestWithDifferentOutput, TestWithDifferentSizes, TestWithDifferentStatuses, TestWithTest, Test\Issue3156Test, Test\Issue3379Test, ThrowExceptionTestCase, ThrowNoExceptionTestCase, TwoTest, WasRun. 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...
29
        $this->services = new ServiceManager();
30
        $this->factory = new SQLLoggerCollectorFactory('orm_default');
31
    }
32
33
    public function testCreateSQLLoggerCollector()
34
    {
35
        $configuration = new ORMConfiguration();
36
        $this->services->setService('doctrine.configuration.orm_default', $configuration);
37
        $this->services->setService(
38
            'config',
39
            [
40
                'doctrine' => [
41
                    'sql_logger_collector' => [
42
                        'orm_default' => [],
43
                    ],
44
                ],
45
            ]
46
        );
47
        $service = $this->factory->createService($this->services);
48
        $this->assertInstanceOf(\DoctrineORMModule\Collector\SQLLoggerCollector::class, $service);
0 ignored issues
show
Bug introduced by
The method assertInstanceOf() does not seem to exist on object<DoctrineORMModule...erCollectorFactoryTest>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
49
        $this->assertInstanceOf(\Doctrine\DBAL\Logging\SQLLogger::class, $configuration->getSQLLogger());
0 ignored issues
show
Bug introduced by
The method assertInstanceOf() does not seem to exist on object<DoctrineORMModule...erCollectorFactoryTest>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
50
    }
51
52
    public function testCreateSQLLoggerWithCustomConfiguration()
53
    {
54
        $configuration = new ORMConfiguration();
55
        $this->services->setService('configuration_service_id', $configuration);
56
        $this->services->setService(
57
            'config',
58
            [
59
                'doctrine' => [
60
                    'sql_logger_collector' => [
61
                        'orm_default' => [
62
                            'configuration' => 'configuration_service_id',
63
                        ],
64
                    ],
65
                ],
66
            ]
67
        );
68
        $this->factory->createService($this->services);
69
        $this->assertInstanceOf(\Doctrine\DBAL\Logging\SQLLogger::class, $configuration->getSQLLogger());
0 ignored issues
show
Bug introduced by
The method assertInstanceOf() does not seem to exist on object<DoctrineORMModule...erCollectorFactoryTest>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
70
    }
71
72
    public function testCreateSQLLoggerWithPreviousExistingLoggerChainsLoggers()
73
    {
74
        $originalLogger = $this->createMock(\Doctrine\DBAL\Logging\SQLLogger::class);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $originalLogger is correct as $this->createMock(\Doctr...gging\SQLLogger::class) (which targets PHPUnit\Framework\TestCase::createMock()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
75
        $originalLogger
0 ignored issues
show
Bug introduced by
The method expects cannot be called on $originalLogger (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
76
            ->expects($this->once())
0 ignored issues
show
Bug introduced by
The method once() does not seem to exist on object<DoctrineORMModule...erCollectorFactoryTest>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
77
            ->method('startQuery')
78
            ->with($this->equalTo('test query'));
0 ignored issues
show
Bug introduced by
The method equalTo() does not seem to exist on object<DoctrineORMModule...erCollectorFactoryTest>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
79
        $injectedLogger = $this->createMock(\Doctrine\DBAL\Logging\DebugStack::class);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $injectedLogger is correct as $this->createMock(\Doctr...ging\DebugStack::class) (which targets PHPUnit\Framework\TestCase::createMock()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
80
        $injectedLogger
0 ignored issues
show
Bug introduced by
The method expects cannot be called on $injectedLogger (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
81
            ->expects($this->once())
0 ignored issues
show
Bug introduced by
The method once() does not seem to exist on object<DoctrineORMModule...erCollectorFactoryTest>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
82
            ->method('startQuery')
83
            ->with($this->equalTo('test query'));
0 ignored issues
show
Bug introduced by
The method equalTo() does not seem to exist on object<DoctrineORMModule...erCollectorFactoryTest>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
84
85
        $configuration = new ORMConfiguration();
86
        $configuration->setSQLLogger($originalLogger);
87
        $this->services->setService('doctrine.configuration.orm_default', $configuration);
88
        $this->services->setService('custom_logger', $injectedLogger);
0 ignored issues
show
Documentation introduced by
$injectedLogger is of type null, but the function expects a array|object.

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...
89
        $this->services->setService(
90
            'config',
91
            [
92
                'doctrine' => [
93
                    'sql_logger_collector' => [
94
                        'orm_default' => [
95
                            'sql_logger' => 'custom_logger',
96
                        ],
97
                    ],
98
                ],
99
            ]
100
        );
101
        $this->factory->createService($this->services);
102
        /* @var $logger \Doctrine\DBAL\Logging\SQLLogger */
103
        $logger = $configuration->getSQLLogger();
104
        $logger->startQuery('test query');
105
    }
106
107
    public function testCreateSQLLoggerWithCustomLogger()
108
    {
109
        $configuration = new ORMConfiguration();
110
        $logger = new DebugStack();
111
        $this->services->setService('doctrine.configuration.orm_default', $configuration);
112
        $this->services->setService('logger_service_id', $logger);
113
        $this->services->setService(
114
            'config',
115
            [
116
                'doctrine' => [
117
                    'sql_logger_collector' => [
118
                        'orm_default' => [
119
                            'sql_logger' => 'logger_service_id',
120
                        ],
121
                    ],
122
                ],
123
            ]
124
        );
125
        $this->factory->createService($this->services);
126
        $this->assertSame($logger, $configuration->getSQLLogger());
0 ignored issues
show
Bug introduced by
The method assertSame() does not seem to exist on object<DoctrineORMModule...erCollectorFactoryTest>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
127
    }
128
129
    public function testCreateSQLLoggerWithCustomName()
130
    {
131
        $this->services->setService('doctrine.configuration.orm_default', new ORMConfiguration());
132
        $this->services->setService(
133
            'config',
134
            [
135
                'doctrine' => [
136
                    'sql_logger_collector' => [
137
                        'orm_default' => [
138
                            'name' => 'test_collector_name',
139
                        ],
140
                    ],
141
                ],
142
            ]
143
        );
144
        /* @var $service \DoctrineORMModule\Collector\SQLLoggerCollector */
145
        $service = $this->factory->createService($this->services);
146
        $this->assertSame('doctrine.sql_logger_collector.test_collector_name', $service->getName());
0 ignored issues
show
Bug introduced by
The method assertSame() does not seem to exist on object<DoctrineORMModule...erCollectorFactoryTest>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
147
    }
148
}
149