ApiResponseFactory   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 96
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 11

Test Coverage

Coverage 96.67%

Importance

Changes 0
Metric Value
wmc 8
lcom 2
cbo 11
dl 0
loc 96
ccs 29
cts 30
cp 0.9667
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 1
A createResponse() 0 16 3
A createImageResponse() 0 8 1
A processCreation() 0 20 2
A createEntityHttpLocation() 0 7 1
1
<?php
2
3
namespace AppBundle\Response;
4
5
use AppBundle\Entity\Image;
6
use AppBundle\Entity\User;
7
use AppBundle\Enum\ApiOperation;
8
use AppBundle\Exception\UnsupportedApiOperation;
9
use AppBundle\Exception\UnsupportedTypeException;
10
use AppBundle\Form\AbstractFormType;
11
use AppBundle\Response\Infrastructure\AbstractApiResponse;
12
use AppBundle\Service\Entity\EntityService;
13
use Doctrine\ORM\EntityManager;
14
use Symfony\Component\Form\FormInterface;
15
use Symfony\Component\HttpFoundation\Response;
16
use Symfony\Component\Routing\Router;
17
18
/**
19
 * @author Vehsamrak
20
 */
21
class ApiResponseFactory
22
{
23
24
    /** @var string */
25
    private $filePath;
26
27
    /** @var EntityManager */
28
    private $entityManager;
29
30
    /** @var EntityService */
31
    private $entityService;
32
33
    /** @var Router */
34
    private $router;
35
36 10
    public function __construct(
37
        string $applicationRootPath,
38
        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...
39
        EntityService $entityService,
40
        Router $router
41
    )
42
    {
43 10
        $this->filePath = realpath($applicationRootPath . '/../var/upload');
44 10
        $this->entityManager = $entityManager;
45 10
        $this->entityService = $entityService;
46 10
        $this->router = $router;
47 10
    }
48
49
    /**
50
     * Api response factory method
51
     * @throws UnsupportedApiOperation
52
     */
53 9
    public function createResponse(
54
        ApiOperation $operation,
55
        FormInterface $form,
56
        User $creator
57
    ): AbstractApiResponse
58
    {
59 9
        if (!$form->isValid()) {
60 4
            return new ApiValidationError($form);
61
        }
62
63 5
        if ($operation->getValue() === ApiOperation::CREATE) {
64 5
            return $this->processCreation($form, $creator);
65
        }
66
67
        throw new UnsupportedApiOperation($operation);
68
    }
69
70
    /**
71
     * @deprecated
72
     * @throws UnsupportedTypeException
73
     */
74 1
    public function createImageResponse(Image $responseData): FileResponse
75
    {
76 1
        $imagesBasePath = $this->filePath . '/images/';
77 1
        $imagePath = $imagesBasePath . $responseData->getName();
78 1
        $response = new FileResponse($imagePath);
79
80 1
        return $response;
81
    }
82
83 5
    private function processCreation(
84
        FormInterface $form,
85
        User $creator
86
    ): AbstractApiResponse
87
    {
88
        /** @var AbstractFormType $formData */
89 5
        $formData = $form->getData();
90 5
        $entityClass = $formData->getEntityClassName();
91
92 5
        $entity = $this->entityService->createEntityByFormData($formData, $creator, $entityClass);
93
94 5
        if (method_exists($entity, 'getId')) {
95 3
            $location = $this->createEntityHttpLocation($entity, $entity->getId());
96 3
            $response = new CreatedApiResponse($location);
97
        } else {
98 2
            $response = new EmptyApiResponse(Response::HTTP_CREATED);
99
        }
100
101 5
        return $response;
102
    }
103
104
    /**
105
     * @param object $entity Entity
106
     * @param string $id Entity id
107
     * @return string
108
     */
109 3
    private function createEntityHttpLocation($entity, string $id): string
110
    {
111 3
        $entityShortName = (new \ReflectionClass($entity))->getShortName();
112 3
        $route = strtolower($entityShortName) . '_view';
113
114 3
        return $this->router->generate($route, ['id' => $id], Router::ABSOLUTE_URL);
115
    }
116
}
117