SQLLoggerCollectorTest::testGetQueryTime()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.6
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace DoctrineORMModuleTest\Collector;
4
5
use PHPUnit\Framework\TestCase;
6
use DoctrineORMModule\Collector\SQLLoggerCollector;
7
use Doctrine\DBAL\Logging\DebugStack;
8
use Laminas\Mvc\MvcEvent;
9
10
class SQLLoggerCollectorTest extends TestCase
11
{
12
    /**
13
     * @var DebugStack
14
     */
15
    protected $logger;
16
17
    /**
18
     * @var string
19
     */
20
    protected $name = 'test-collector-name';
21
22
    /**
23
     * @var SQLLoggerCollector
24
     */
25
    protected $collector;
26
27
    public function setUp() : void
28
    {
29
        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...
30
        $this->logger = new DebugStack();
31
        $this->collector = new SQLLoggerCollector($this->logger, $this->name);
32
    }
33
34
    public function testHasCorrectName()
35
    {
36
        $this->assertSame($this->name, $this->collector->getName());
0 ignored issues
show
Bug introduced by
The method assertSame() does not seem to exist on object<DoctrineORMModule...SQLLoggerCollectorTest>.

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...
37
    }
38
39
    public function testGetPriority()
40
    {
41
        $this->assertIsInt($this->collector->getPriority());
0 ignored issues
show
Bug introduced by
The method assertIsInt() does not seem to exist on object<DoctrineORMModule...SQLLoggerCollectorTest>.

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...
42
    }
43
44
    public function testCollect()
45
    {
46
        $this->collector->collect(new MvcEvent());
47
        $this->addToAssertionCount(1);
0 ignored issues
show
Bug introduced by
The method addToAssertionCount() does not seem to exist on object<DoctrineORMModule...SQLLoggerCollectorTest>.

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...
48
    }
49
50
    public function testCanHide()
51
    {
52
        $this->assertTrue($this->collector->canHide());
0 ignored issues
show
Bug introduced by
The method assertTrue() does not seem to exist on object<DoctrineORMModule...SQLLoggerCollectorTest>.

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...
53
        $this->logger->startQuery('some sql');
54
        $this->assertFalse($this->collector->canHide());
0 ignored issues
show
Bug introduced by
The method assertFalse() does not seem to exist on object<DoctrineORMModule...SQLLoggerCollectorTest>.

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...
55
    }
56
57
    public function testGetQueryCount()
58
    {
59
        $this->assertSame(0, $this->collector->getQueryCount());
0 ignored issues
show
Bug introduced by
The method assertSame() does not seem to exist on object<DoctrineORMModule...SQLLoggerCollectorTest>.

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...
60
        $this->logger->startQuery('some sql');
61
        $this->assertSame(1, $this->collector->getQueryCount());
0 ignored issues
show
Bug introduced by
The method assertSame() does not seem to exist on object<DoctrineORMModule...SQLLoggerCollectorTest>.

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...
62
        $this->logger->startQuery('some more sql');
63
        $this->assertSame(2, $this->collector->getQueryCount());
0 ignored issues
show
Bug introduced by
The method assertSame() does not seem to exist on object<DoctrineORMModule...SQLLoggerCollectorTest>.

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...
64
    }
65
66
    public function testGetQueryTime()
67
    {
68
        $start = microtime(true);
69
        $this->assertEquals(0, $this->collector->getQueryTime());
0 ignored issues
show
Bug introduced by
The method assertEquals() does not seem to exist on object<DoctrineORMModule...SQLLoggerCollectorTest>.

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
        $this->logger->startQuery('some sql');
72
        sleep(1);
73
        $this->logger->stopQuery();
74
        $time = microtime(true) - $start;
75
        $time1 = $this->collector->getQueryTime();
76
        $this->assertGreaterThan(0, $time1);
0 ignored issues
show
Bug introduced by
The method assertGreaterThan() does not seem to exist on object<DoctrineORMModule...SQLLoggerCollectorTest>.

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
        $this->assertLessThan($time, $time1);
0 ignored issues
show
Bug introduced by
The method assertLessThan() does not seem to exist on object<DoctrineORMModule...SQLLoggerCollectorTest>.

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...
78
79
        $this->logger->startQuery('some more sql');
80
        $this->logger->stopQuery();
81
        $time = microtime(true) - $start;
82
        $time2 = $this->collector->getQueryTime();
83
        $this->assertGreaterThan($time1, $time2);
0 ignored issues
show
Bug introduced by
The method assertGreaterThan() does not seem to exist on object<DoctrineORMModule...SQLLoggerCollectorTest>.

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
        $this->assertLessThan($time, $time1);
0 ignored issues
show
Bug introduced by
The method assertLessThan() does not seem to exist on object<DoctrineORMModule...SQLLoggerCollectorTest>.

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...
85
    }
86
}
87