Completed
Push — refonte ( 64e01a...7173e3 )
by Arnaud
03:31
created

AdminTestBaseOLD::mockDoctrine()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace LAG\AdminBundle\Tests;
4
5
use Closure;
6
use Doctrine\Bundle\DoctrineBundle\Registry;
7
use Doctrine\ORM\EntityManager;
8
use Doctrine\ORM\EntityManagerInterface;
9
use Doctrine\ORM\Mapping\ClassMetadata;
10
use Exception;
11
use Knp\Menu\MenuFactory;
12
use LAG\AdminBundle\Action\ActionInterface;
13
use LAG\AdminBundle\Admin\Admin;
14
use LAG\AdminBundle\Action\Configuration\ActionConfiguration;
15
use LAG\AdminBundle\Admin\Configuration\AdminConfiguration;
16
use LAG\AdminBundle\Application\Configuration\ApplicationConfiguration;
17
use LAG\AdminBundle\Action\Factory\ActionFactory;
18
use LAG\AdminBundle\DataProvider\DataProviderInterface;
19
use LAG\AdminBundle\Field\Factory\FieldFactory;
20
use LAG\AdminBundle\Message\MessageHandlerInterface;
21
use LAG\AdminBundle\Repository\RepositoryInterface;
22
use PHPUnit\Framework\TestCase;
23
use PHPUnit_Framework_MockObject_MockObject;
24
use ReflectionClass;
25
use Symfony\Bridge\Monolog\Logger;
26
use Symfony\Component\DependencyInjection\ContainerInterface;
27
use Symfony\Component\HttpFoundation\Request;
28
use Symfony\Component\HttpFoundation\Session\Session;
29
use Symfony\Component\HttpKernel\KernelInterface;
30
use Symfony\Component\OptionsResolver\OptionsResolver;
31
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
32
use Symfony\Component\Translation\TranslatorInterface;
33
34
class AdminTestBaseOLD extends TestCase
35
{
36
    /**
37
     * @var bool
38
     */
39
    protected static $isDatabaseCreated = false;
40
41
    /**
42
     * @var ContainerInterface
43
     */
44
    protected $container;
45
46
    /**
47
     * @var Client
48
     */
49
    protected $client;
50
51
    /**
52
     * Initialize an application with a container and a client. Create database if required.
53
     *
54
     * @param string $url
55
     * @param null $method
56
     * @param array $parameters
57
     */
58
    public function initApplication($url = '/', $method = null, $parameters = [])
59
    {
60
        // creating kernel client
61
        $this->client = Client::initClient();
62
        // test client initialization
63
        $this->assertTrue($this->client != null, 'TestClient successfully initialized');
64
65
        // initialise database
66
        if (!self::$isDatabaseCreated) {
67
            // TODO remove database at the end of the tests
68
            exec(__DIR__ . '/app/console doctrine:database:create --if-not-exists', $output);
69
            exec(__DIR__ . '/app/console doctrine:schema:update --force', $output);
70
71
            foreach ($output as $line) {
0 ignored issues
show
Bug introduced by
The expression $output of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
72
                // TODO only in verbose mode
73
                fwrite(STDOUT, $line . "\n");
74
            }
75
            fwrite(STDOUT, "\n");
76
            self::$isDatabaseCreated = true;
77
        }
78
        // init a request
79
        $request = Request::create($url, $method, $parameters);
80
        // do request
81
        $this->client->doRequest($request);
82
        $this->container = $this->client->getContainer();
83
    }
84
85
    /**
86
     * Assert that an exception is raised in the given code.
87
     *
88
     * @param $exceptionClass
89
     * @param Closure $closure
90
     */
91 View Code Duplication
    protected function assertExceptionRaised($exceptionClass, Closure $closure)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
92
    {
93
        $e = null;
94
        $isClassValid = false;
95
        $message = '';
96
97
        try {
98
            $closure();
99
        } catch (Exception $e) {
100
            if (get_class($e) == $exceptionClass) {
101
                $isClassValid = true;
102
            }
103
            $message = $e->getMessage();
104
        }
105
        $this->assertNotNull($e, 'No Exception was thrown');
106
        $this->assertTrue($isClassValid, sprintf('Expected %s, got %s (Exception message : "%s")',
107
            $exceptionClass,
108
            get_class($e),
109
            $message
110
        ));
111
    }
112
113
    /**
114
     * @param ApplicationConfiguration $applicationConfiguration
115
     * @param array $configuration
116
     * @return AdminConfiguration
117
     */
118
    protected function createAdminConfiguration(ApplicationConfiguration $applicationConfiguration, array $configuration = [])
119
    {
120
        $resolver = new OptionsResolver();
121
        $adminConfiguration = new AdminConfiguration($applicationConfiguration);
122
        $adminConfiguration->configureOptions($resolver);
123
        $adminConfiguration->setParameters($resolver->resolve($configuration));
124
125
        return $adminConfiguration;
126
    }
127
128
    /**
129
     * @return MenuFactory
130
     */
131
    protected function createKnpMenuFactory()
132
    {
133
        return new MenuFactory();
134
    }
135
    
136
    /**
137
     * Return Admin configurations samples
138
     *
139
     * @return array
140
     */
141
    protected function getAdminsConfiguration()
142
    {
143
        return [
144
            'minimal_configuration' => [
145
                'entity' => 'Test\TestBundle\Entity\TestEntity',
146
                'form' => 'test'
147
            ],
148
            'full_configuration' => [
149
                'entity' => 'Test\TestBundle\Entity\TestEntity',
150
                'form' => 'test',
151
                'controller' => 'TestTestBundle:Test',
152
                'max_per_page' => 50,
153
                'actions' => [
154
                    'custom_list' => [],
155
                    'custom_edit' => [],
156
                ],
157
                'routing_url_pattern' => 'lag.admin.{admin}',
158
                'routing_name_pattern' => 'lag.{admin}.{action}'
159
            ]
160
        ];
161
    }
162
163
    /**
164
     * @return KernelInterface | PHPUnit_Framework_MockObject_MockObject
165
     */
166
    protected function mockKernel()
167
    {
168
        return $this
169
            ->getMockBuilder(KernelInterface::class)
170
            ->disableOriginalConstructor()
171
            ->getMock();
172
    }
173
174
    /**
175
     * @param $name
176
     * @return ActionInterface | PHPUnit_Framework_MockObject_MockObject
177
     */
178
    protected function mockAction($name)
179
    {
180
        $action = $this
181
            ->getMockBuilder(ActionInterface::class)
182
            ->disableOriginalConstructor()
183
            ->getMock();
184
        $action
185
            ->method('getName')
186
            ->willReturn($name);
187
188
        return $action;
189
    }
190
191
    /**
192
     * @return ActionConfiguration | PHPUnit_Framework_MockObject_MockObject
193
     */
194
    protected function mockActionConfiguration()
195
    {
196
        $configuration = $this
197
            ->getMockBuilder('LAG\AdminBundle\Admin\Configuration\ActionConfiguration')
198
            ->disableOriginalConstructor()
199
            ->getMock();
200
        $configuration
201
            ->method('getLoadMethod')
202
            ->willReturn(Admin::LOAD_STRATEGY_MULTIPLE);
203
        $configuration
204
            ->method('getCriteria')
205
            ->willReturn([]);
206
207
        return $configuration;
208
    }
209
210
    /**
211
     * @return Session | PHPUnit_Framework_MockObject_MockObject
212
     */
213 View Code Duplication
    protected function mockSession()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
214
    {
215
        if ($this->container) {
216
            $session = $this
217
                ->container
218
                ->get('session');
219
        } else {
220
            $session = $this
221
                ->getMockBuilder('Symfony\Component\HttpFoundation\Session\Session')
222
                ->disableOriginalConstructor()
223
                ->getMock();
224
        }
225
        return $session;
226
    }
227
228
    /**
229
     * @return Logger | PHPUnit_Framework_MockObject_MockObject
230
     */
231 View Code Duplication
    protected function mockLogger()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
232
    {
233
        if ($this->container) {
234
            $logger = $this
235
                ->container
236
                ->get('logger');
237
        } else {
238
            $logger = $this
239
                ->getMockBuilder('Monolog\Logger')
240
                ->disableOriginalConstructor()
241
                ->getMock();
242
        }
243
        return $logger;
244
    }
245
246
    /**
247
     * Return a mock of an entity repository
248
     *
249
     * @return RepositoryInterface | PHPUnit_Framework_MockObject_MockObject
250
     */
251
    protected function mockEntityRepository()
252
    {
253
        return $this
254
            ->getMockBuilder(RepositoryInterface::class)
255
            ->getMock();
256
    }
257
258
    /**
259
     * @return EntityManager | PHPUnit_Framework_MockObject_MockObject
260
     */
261
    protected function mockEntityManager()
262
    {
263
        /** @var EntityManagerInterface | PHPUnit_Framework_MockObject_MockObject $entityManager */
264
        $entityManager = $this
265
            ->getMockBuilder('Doctrine\ORM\EntityManager')
266
            ->disableOriginalConstructor()
267
            ->getMock();
268
        $repository = $this->mockEntityRepository();
269
270
        $entityManager
271
            ->method('getRepository')
272
            ->willReturn($repository);
273
        $entityManager
274
            ->method('getClassMetadata')
275
            ->willReturn(new ClassMetadata('LAG\AdminBundle\Tests\Entity\TestEntity'));
276
277
        return $entityManager;
278
    }
279
280
    /**
281
     * @return Registry | PHPUnit_Framework_MockObject_MockObject
282
     *
283
     * @deprecated
284
     */
285
    protected function mockDoctrine()
286
    {
287
        $doctrine = $this
288
            ->getMockBuilder(Registry::class)
289
            ->disableOriginalConstructor()
290
            ->getMock();
291
        $doctrine
292
            ->method('getEntityManager')
293
            ->willReturn($this->mockEntityManager());
294
295
        return $doctrine;
296
    }
297
298
    /**
299
     * @return ActionFactory | PHPUnit_Framework_MockObject_MockObject
300
     */
301
    protected function mockActionFactory()
302
    {
303
        $actionFactory = $this
304
            ->getMockBuilder(ActionFactory::class)
305
            ->disableOriginalConstructor()
306
            ->getMock();
307
        $actionFactory
308
            ->method('create')
309
            ->willReturn($this->mockAction('test'));
310
311
        return $actionFactory;
312
    }
313
314
    /**
315
     * @return TokenStorageInterface | PHPUnit_Framework_MockObject_MockObject
316
     */
317
    protected function mockTokenStorage()
318
    {
319
        return $this
320
            ->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')
321
            ->getMock();
322
    }
323
324
    /**
325
     * @return ApplicationConfiguration|PHPUnit_Framework_MockObject_MockObject
326
     */
327
    protected function mockApplicationConfiguration()
328
    {
329
        $applicationConfiguration = $this
330
            ->getMockBuilder('LAG\AdminBundle\Admin\Configuration\ApplicationConfiguration')
331
            ->disableOriginalConstructor()
332
            ->getMock();
333
        $applicationConfiguration
334
            ->method('getMaxPerPage')
335
            ->willReturn(25);
336
337
        return $applicationConfiguration;
338
    }
339
340
    /**
341
     * @return MessageHandlerInterface | PHPUnit_Framework_MockObject_MockObject
342
     */
343
    protected function mockMessageHandler()
344
    {
345
        $messageHandler = $this
346
            ->getMockBuilder('LAG\AdminBundle\Message\MessageHandler')
347
            ->disableOriginalConstructor()
348
            ->getMock();
349
350
        return $messageHandler;
351
    }
352
353
    /**
354
     * @return TranslatorInterface | PHPUnit_Framework_MockObject_MockObject
355
     */
356
    protected function mockTranslator()
357
    {
358
        return $this
359
            ->getMockBuilder('Symfony\Component\Translation\TranslatorInterface')
360
            ->getMock();
361
    }
362
363
    /**
364
     * @param array $entities
365
     * @return DataProviderInterface|PHPUnit_Framework_MockObject_MockObject
366
     */
367
    protected function mockDataProvider($entities = [])
368
    {
369
        $dataProvider = $this
370
            ->getMockBuilder('LAG\AdminBundle\DataProvider\DataProviderInterface')
371
            ->getMock();
372
        $dataProvider
373
            ->method('findBy')
374
            ->willReturn($entities);
375
376
        return $dataProvider;
377
    }
378
379
    /**
380
     * @return FieldFactory|PHPUnit_Framework_MockObject_MockObject
381
     */
382
    protected function mockFieldFactory()
383
    {
384
        $fieldFactory = $this
385
            ->getMockBuilder(FieldFactory::class)
386
            ->disableOriginalConstructor()
387
            ->getMock();
388
389
        return $fieldFactory;
390
    }
391
    
392
    /**
393
     * @param $class
394
     *
395
     * @return PHPUnit_Framework_MockObject_MockObject|mixed
396
     */
397
    protected function getMockWithoutConstructor($class)
398
    {
399
        return $this
400
            ->getMockBuilder($class)
401
            ->disableOriginalConstructor()
402
            ->getMock()
403
        ;
404
    }
405
    
406 View Code Duplication
    protected function setPrivateProperty($object, $property, $value)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
407
    {
408
        $reflection = new ReflectionClass($object);
409
        
410
        $property = $reflection->getProperty($property);
411
        $property->setAccessible(true);
412
        $property->setValue($object, $value);
413
    }
414
    
415 View Code Duplication
    protected function getPrivateProperty($object, $property)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
416
    {
417
        $reflection = new ReflectionClass($object);
418
        
419
        $property = $reflection->getProperty($property);
420
        $property->setAccessible(true);
421
        
422
        return $property->getValue($object);
423
    }
424
}
425