Passed
Push — master ( 1b9891...006f9a )
by Petr
04:14
created

ApiResponseFactory   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 99
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 12

Test Coverage

Coverage 85.29%

Importance

Changes 0
Metric Value
wmc 11
c 0
b 0
f 0
lcom 2
cbo 12
dl 0
loc 99
ccs 29
cts 34
cp 0.8529
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 1
A createResponse() 0 15 3
A createImageResponse() 0 12 2
A createNotFoundResponse() 0 4 1
A processCreation() 0 15 2
A createEntityHttpLocation() 0 13 2
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 6
    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 6
        $this->filePath = realpath($applicationRootPath . '/../var/upload');
45 6
        $this->entityManager = $entityManager;
46 6
        $this->entityService = $entityService;
47 6
        $this->router = $router;
48 6
    }
49
50
    /**
51
     * Api response factory method
52
     */
53 5
    public function createResponse(
54
        ApiOperation $operation,
55
        FormInterface $form,
56
        User $creator,
57
        string $entityClass = null
58
    ): AbstractApiResponse
59
    {
60 5
        if (!$form->isValid()) {
61 3
            return new ApiValidationError($form);
62
        }
63
64 2
        if ($operation->getValue() === ApiOperation::CREATE) {
65 2
            return $this->processCreation($form, $creator, $entityClass);
66
        }
67
    }
68
69
    /**
70
     * @deprecated
71
     * @throws UnsupportedTypeException
72
     */
73 1
    public function createImageResponse($responseData): FileResponse
74
    {
75 1
        if ($responseData instanceof Image) {
76 1
            $imagesBasePath = $this->filePath . '/images/';
77 1
            $imagePath = $imagesBasePath . $responseData->getName();
78 1
            $response = new FileResponse($imagePath);
79
        } else {
80
            throw new UnsupportedTypeException();
81
        }
82
83 1
        return $response;
84
    }
85
86
    public function createNotFoundResponse(): ApiError
87
    {
88
        return new ApiError('Resource was not found.', Response::HTTP_NOT_FOUND);
89
    }
90
91 2
    private function processCreation(
92
        FormInterface $form,
93
        User $creator,
94
        string $entityClass = null
95
    ): AbstractApiResponse
96
    {
97
        /** @var AbstractFormType $formData */
98 2
        $formData = $form->getData();
99 2
        $entityClass = $entityClass ?: $formData->getEntityClassName();
100
101 2
        $entity = $this->entityService->createEntityByFormData($formData, $creator, $entityClass);
102 2
        $location = $this->createEntityHttpLocation($entity);
103
104 2
        return new CreatedApiResponse($location);
105
    }
106
107 2
    private function createEntityHttpLocation($entity): string
108
    {
109 2
        $entityShortName = (new \ReflectionClass($entity))->getShortName();
110 2
        $route = strtolower($entityShortName) . '_view';
111
112 2
        if (method_exists($entity, 'getId')) {
113 2
            $id = $entity->getId();
114
        } else {
115
            throw new MethodNotImplementedException('getId');
116
        }
117
118 2
        return $this->router->generate($route, ['id' => $id], Router::ABSOLUTE_URL);
119
    }
120
}
121