Passed
Push — master ( 25c2e9...26c6a8 )
by Petr
08:32
created

ApiResponseFactory::createResponse()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 5
cts 6
cp 0.8333
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 10
nc 3
nop 4
crap 3.0416
1
<?php
2
3
namespace AppBundle\Response;
4
5
use AppBundle\Entity\Image;
6
use AppBundle\Entity\Infrasctucture\AbstractRepository;
7
use AppBundle\Entity\User;
8
use AppBundle\Enum\ApiOperation;
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\Intl\Exception\MethodNotImplementedException;
17
use Symfony\Component\Routing\Router;
18
19
/**
20
 * @author Vehsamrak
21
 */
22
class ApiResponseFactory
23
{
24
25
    /** @var string */
26
    private $filePath;
27
28
    /** @var EntityManager */
29
    private $entityManager;
30
31
    /** @var EntityService */
32
    private $entityService;
33
34
    /** @var Router */
35
    private $router;
36
37 5
    public function __construct(
38
        string $applicationRootPath,
39
        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...
40
        EntityService $entityService,
41
        Router $router
42
    )
43
    {
44 5
        $this->filePath = realpath($applicationRootPath . '/../var/upload');
45 5
        $this->entityManager = $entityManager;
46 5
        $this->entityService = $entityService;
47 5
        $this->router = $router;
48 5
    }
49
50 4
    public function createResponse(
51
        ApiOperation $operation,
52
        FormInterface $form,
53
        User $creator,
54
        string $entityClass = null
55
    ): AbstractApiResponse
56
    {
57 4
        if (!$form->isValid()) {
58 2
            return new ApiValidationError($form);
59
        }
60
61 2
        if ($operation->getValue() === ApiOperation::CREATE) {
62 2
            return $this->processCreation($form, $creator, $entityClass);
63
        }
64
    }
65
66
    /**
67
     * @deprecated
68
     * @throws UnsupportedTypeException
69
     */
70 1
    public function createImageResponse($responseData): FileResponse
71
    {
72 1
        if ($responseData instanceof Image) {
73 1
            $imagesBasePath = $this->filePath . '/images/';
74 1
            $imagePath = $imagesBasePath . $responseData->getName();
75 1
            $response = new FileResponse($imagePath);
76
        } else {
77
            throw new UnsupportedTypeException();
78
        }
79
80 1
        return $response;
81
    }
82
83
    public function createNotFoundResponse(): ApiError
84
    {
85
        return new ApiError('Resource was not found.', Response::HTTP_NOT_FOUND);
86
    }
87
88 2
    private function processCreation(
89
        FormInterface $form,
90
        User $creator,
91
        string $entityClass = null
92
    ): AbstractApiResponse
93
    {
94
        /** @var AbstractFormType $formData */
95 2
        $formData = $form->getData();
96 2
        $entityClass = $entityClass ?: $formData->getEntityClassName();
97
        /** @var AbstractRepository $repository */
98 2
        $repository = $this->entityManager->getRepository($entityClass);
99 2
        $entity = $repository->findOneByFormData($formData);
100
101 2
        if ($entity) {
102
            return new ApiValidationError('Entity with given id already exists.');
103
        }
104
105 2
        $entity = $this->entityService->createEntityByFormData($formData, $creator, $entityClass);
106 2
        $location = $this->createEntityHttpLocation($entity);
107
108 2
        return new CreatedApiResponse($location);
109
    }
110
111 2
    private function createEntityHttpLocation($entity): string
112
    {
113 2
        $entityShortName = (new \ReflectionClass($entity))->getShortName();
114 2
        $route = strtolower($entityShortName) . '_view';
115
116 2
        if (method_exists($entity, 'getId')) {
117 2
            $id = $entity->getId();
118
        } else {
119
            throw new MethodNotImplementedException('getId');
120
        }
121
122 2
        return $this->router->generate($route, ['id' => $id], Router::ABSOLUTE_URL);
123
    }
124
}
125