Completed
Push — master ( 7d656f...5c578b )
by
unknown
10s
created

ProxyQueryTest::testGetFixedQueryBuilder()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 84
Code Lines 67

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 84
rs 8.7169
c 0
b 0
f 0
cc 1
eloc 67
nc 1
nop 6

How to fix   Long Method   

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
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Sonata Project package.
7
 *
8
 * (c) Thomas Rabaix <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Sonata\DoctrineORMAdminBundle\Tests\Datagrid;
15
16
use Doctrine\DBAL\Connection;
17
use Doctrine\DBAL\Platforms\PostgreSqlPlatform;
18
use Doctrine\DBAL\Types\Type;
19
use Doctrine\ORM\EntityManager;
20
use Doctrine\ORM\Mapping\ClassMetadata;
21
use Doctrine\ORM\Mapping\ClassMetadataFactory;
22
use Doctrine\ORM\Query;
23
use Doctrine\ORM\Query\Expr\From;
24
use Doctrine\ORM\Query\Expr\OrderBy;
25
use Doctrine\ORM\QueryBuilder;
26
use Doctrine\ORM\Tools\SchemaTool;
27
use PHPUnit\Framework\TestCase;
28
use Sonata\DoctrineORMAdminBundle\Datagrid\ProxyQuery;
29
use Sonata\DoctrineORMAdminBundle\Tests\Fixtures\DoctrineType\UuidType;
30
use Sonata\DoctrineORMAdminBundle\Tests\Fixtures\Query\FooWalker;
31
use Sonata\DoctrineORMAdminBundle\Tests\Fixtures\Util\NonIntegerIdentifierTestClass;
32
use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper;
33
use Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNameEntity;
34
35
class ProxyQueryTest extends TestCase
36
{
37
    /**
38
     * @var EntityManager
39
     */
40
    private $em;
41
42
    public static function setUpBeforeClass(): void
43
    {
44
        if (!Type::hasType('uuid')) {
45
            Type::addType('uuid', UuidType::class);
46
        }
47
    }
48
49
    protected function setUp(): void
50
    {
51
        $this->em = DoctrineTestHelper::createTestEntityManager();
52
53
        $schemaTool = new SchemaTool($this->em);
54
        $classes = [
55
            $this->em->getClassMetadata(DoubleNameEntity::class),
56
        ];
57
58
        try {
59
            $schemaTool->dropSchema($classes);
60
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
61
        }
62
63
        try {
64
            $schemaTool->createSchema($classes);
65
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
66
        }
67
    }
68
69
    protected function tearDown(): void
70
    {
71
        $this->em = null;
72
    }
73
74
    public function dataGetFixedQueryBuilder()
75
    {
76
        return [
77
            ['aaa', 'bbb', 'id', 'id_idx', 33, Type::INTEGER],
78
            ['aaa', 'bbb', 'associatedId', 'associatedId_idx', 33, null],
79
            ['aaa', 'bbb', 'id.value', 'id_value_idx', 33, Type::INTEGER],
80
            ['aaa', 'bbb', 'id.uuid', 'id_uuid_idx', new NonIntegerIdentifierTestClass('80fb6f91-bba1-4d35-b3d4-e06b24494e85'), UuidType::NAME],
81
        ];
82
    }
83
84
    /**
85
     * @dataProvider dataGetFixedQueryBuilder
86
     *
87
     * @param $class
88
     * @param $alias
89
     * @param $id
90
     */
91
    public function testGetFixedQueryBuilder($class, $alias, $id, $expectedId, $value, $identifierType): void
92
    {
93
        $meta = $this->createMock(ClassMetadata::class);
94
        $meta->expects($this->any())
95
            ->method('getIdentifierFieldNames')
96
            ->willReturn([$id]);
97
        $meta->expects($this->any())
98
            ->method('getTypeOfField')
99
            ->willReturn($identifierType);
100
101
        $mf = $this->createMock(ClassMetadataFactory::class);
102
        $mf->expects($this->any())
103
            ->method('getMetadataFor')
104
            ->with($this->equalTo($class))
105
            ->willReturn($meta);
106
107
        $platform = $this->createMock(PostgreSqlPlatform::class);
108
109
        $conn = $this->createMock(Connection::class);
110
        $conn->expects($this->any())
111
            ->method('getDatabasePlatform')
112
            ->willReturn($platform);
113
114
        $em = $this->createMock(EntityManager::class);
115
        $em->expects($this->any())
116
            ->method('getMetadataFactory')
117
            ->willReturn($mf);
118
        $em->expects($this->any())
119
            ->method('getConnection')
120
            ->willReturn($conn);
121
122
        // NEXT MAJOR: Replace this when dropping PHP < 5.6
123
        // $q = $this->createMock('PDOStatement');
124
        $q = $this->getMockBuilder('stdClass')
125
            ->setMethods(['execute', 'setHint'])
126
            ->getMock();
127
        $q->expects($this->once())
128
           ->method('setHint')
129
           ->willReturn($q);
130
        $q->expects($this->any())
131
            ->method('execute')
132
            ->willReturn([[$id => $value]]);
133
134
        $qb = $this->getMockBuilder(QueryBuilder::class)
135
            ->setConstructorArgs([$em])
136
            ->getMock();
137
        $qb->expects($this->any())
138
            ->method('getEntityManager')
139
            ->willReturn($em);
140
        $qb->expects($this->any())
141
            ->method('getQuery')
142
            ->willReturn($q);
143
        $qb->expects($this->once())
144
            ->method('setParameter')
145
            ->with($this->equalTo($expectedId), $this->equalTo([$value]));
146
        $qb->expects($this->any())
147
            ->method('getDQLPart')
148
            ->will($this->returnCallBack(function ($part) use ($class, $alias) {
149
                $parts = [
150
                    'from' => [new From($class, $alias)],
151
                    'orderBy' => [new OrderBy('whatever', 'DESC')],
152
                ];
153
154
                return $parts[$part];
155
            }));
156
        $qb->expects($this->once())
157
            ->method('addOrderBy')
158
            ->with("$alias.$id", null);
159
        $qb->expects($this->once())
160
            ->method('getRootEntities')
161
            ->willReturn([$class]);
162
        $qb->expects($this->exactly(2))
163
            ->method('getRootAliases')
164
            ->willReturn([$alias]);
165
166
        $pq = $this->getMockBuilder(ProxyQuery::class)
167
            ->setConstructorArgs([$qb])
168
            ->setMethods(['a'])
169
            ->getMock();
170
171
        /* Work */
172
173
        $pq->execute();
174
    }
175
176
    public function testSetHint(): void
177
    {
178
        $entity1 = new DoubleNameEntity(1, 'Foo', null);
179
        $entity2 = new DoubleNameEntity(2, 'Bar', null);
180
181
        $this->em->persist($entity1);
182
        $this->em->persist($entity2);
183
        $this->em->flush();
184
185
        $qb = $this->em->createQueryBuilder()
186
            ->select('o.id')
187
            ->from(DoubleNameEntity::class, 'o');
188
189
        $pq = new ProxyQuery($qb);
190
        $pq->setHint(
191
            Query::HINT_CUSTOM_OUTPUT_WALKER,
192
            FooWalker::class
193
        );
194
        $pq->setHint('hint', 'value');
195
196
        $result = $pq->execute();
197
198
        $this->assertEquals(2, $result[0]['id']);
199
    }
200
201
    public function testSortOrderValidatesItsInput(): void
202
    {
203
        $query = new ProxyQuery($this->em->createQueryBuilder());
204
        $this->expectException(\InvalidArgumentException::class);
205
        $this->expectExceptionMessage(
206
            '"ASC,injection" is not a valid sort order, valid values are "ASC, DESC"'
207
        );
208
        $query->setSortOrder('ASC,injection');
209
    }
210
211
    public function validSortOrders()
212
    {
213
        return [
214
            ['ASC'],
215
            ['DESC'],
216
            ['asc'],
217
            ['desc'],
218
            ['AsC'],
219
            ['deSc'],
220
        ];
221
    }
222
223
    /**
224
     * @dataProvider validSortOrders
225
     */
226
    public function testItAllowsSortOrdersWithStrangeCase($validValue): void
227
    {
228
        $query = new ProxyQuery($this->em->createQueryBuilder());
229
        $query->setSortOrder($validValue);
230
        $this->assertSame($validValue, $query->getSortOrder());
231
    }
232
}
233