DatabaseLoader   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 3
lcom 1
cbo 3
dl 0
loc 44
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A prepareCategoryTableWithTwoItems() 0 16 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Zenify\DoctrineExtensionsTree\Tests;
6
7
use Doctrine\DBAL\Connection;
8
use Doctrine\ORM\EntityManager;
9
use Zenify\DoctrineExtensionsTree\Tests\Project\Entities\Category;
10
11
12
final class DatabaseLoader
13
{
14
15
	/**
16
	 * @var bool
17
	 */
18
	private $isDbSchemaPrepared = FALSE;
19
20
	/**
21
	 * @var Connection
22
	 */
23
	private $connection;
24
25
	/**
26
	 * @var EntityManager
27
	 */
28
	private $entityManager;
29
30
31
	public function __construct(Connection $connection, EntityManager $entityManager)
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $entityManager. This is generally not recommended as it might get closed and become unusable. Instead, it is recommended to inject the ManagerRegistry and retrieve the EntityManager via getManager() each time you need it.

The EntityManager might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:

function someFunction(ManagerRegistry $registry) {
    $em = $registry->getManager();
    $em->getConnection()->beginTransaction();
    try {
        // Do something.
        $em->getConnection()->commit();
    } catch (\Exception $ex) {
        $em->getConnection()->rollback();
        $em->close();

        throw $ex;
    }
}

If that code throws an exception and the EntityManager is closed. Any other code which depends on the same instance of the EntityManager during this request will fail.

On the other hand, if you instead inject the ManagerRegistry, the getManager() method guarantees that you will always get a usable manager instance.

Loading history...
32
	{
33
		$this->connection = $connection;
34
		$this->entityManager = $entityManager;
35
	}
36
37
38
	public function prepareCategoryTableWithTwoItems()
39
	{
40
		if ( ! $this->isDbSchemaPrepared) {
41
			/** @var Connection $connection */
42
			$this->connection->query('CREATE TABLE category (id INTEGER NOT NULL, parent_id int NULL,'
43
				. 'path string, name string, PRIMARY KEY(id))');
44
45
			$fruitCategory = new Category('Fruit');
46
			$appleCategory = new Category('Apple', $fruitCategory);
47
48
			$this->entityManager->persist($fruitCategory);
49
			$this->entityManager->persist($appleCategory);
50
			$this->entityManager->flush();
51
			$this->isDbSchemaPrepared = TRUE;
52
		}
53
	}
54
55
}
56