Passed
Push — master ( 21a45d...334091 )
by Petr
03:48
created

ApiResponseFactory::createResponse()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 5
cts 6
cp 0.8333
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 10
nc 3
nop 3
crap 3.0416
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\MethodNotImplemented;
9
use AppBundle\Exception\UnsupportedApiOperation;
10
use AppBundle\Exception\UnsupportedTypeException;
11
use AppBundle\Form\AbstractFormType;
12
use AppBundle\Response\Infrastructure\AbstractApiResponse;
13
use AppBundle\Service\Entity\EntityService;
14
use Doctrine\ORM\EntityManager;
15
use Symfony\Component\Form\FormInterface;
16
use Symfony\Component\HttpFoundation\Response;
17
use Symfony\Component\Intl\Exception\MethodNotImplementedException;
18
use Symfony\Component\Routing\Router;
19
20
/**
21
 * @author Vehsamrak
22
 */
23
class ApiResponseFactory
24
{
25
26
    /** @var string */
27
    private $filePath;
28
29
    /** @var EntityManager */
30
    private $entityManager;
31
32
    /** @var EntityService */
33
    private $entityService;
34
35
    /** @var Router */
36
    private $router;
37
38 8
    public function __construct(
39
        string $applicationRootPath,
40
        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...
41
        EntityService $entityService,
42
        Router $router
43
    )
44
    {
45 8
        $this->filePath = realpath($applicationRootPath . '/../var/upload');
46 8
        $this->entityManager = $entityManager;
47 8
        $this->entityService = $entityService;
48 8
        $this->router = $router;
49 8
    }
50
51
    /**
52
     * Api response factory method
53
     * @throws UnsupportedApiOperation
54
     */
55 7
    public function createResponse(
56
        ApiOperation $operation,
57
        FormInterface $form,
58
        User $creator
59
    ): AbstractApiResponse
60
    {
61 7
        if (!$form->isValid()) {
62 3
            return new ApiValidationError($form);
63
        }
64
65 4
        if ($operation->getValue() === ApiOperation::CREATE) {
66 4
            return $this->processCreation($form, $creator);
67
        }
68
69
        throw new UnsupportedApiOperation($operation);
70
    }
71
72
    /**
73
     * @deprecated
74
     * @throws UnsupportedTypeException
75
     */
76 1
    public function createImageResponse($responseData): FileResponse
77
    {
78 1
        if ($responseData instanceof Image) {
79 1
            $imagesBasePath = $this->filePath . '/images/';
80 1
            $imagePath = $imagesBasePath . $responseData->getName();
81 1
            $response = new FileResponse($imagePath);
82
        } else {
83
            throw new UnsupportedTypeException();
84
        }
85
86 1
        return $response;
87
    }
88
89
    public function createNotFoundResponse(): ApiError
90
    {
91
        return new ApiError('Resource was not found.', Response::HTTP_NOT_FOUND);
92
    }
93
94 4
    private function processCreation(
95
        FormInterface $form,
96
        User $creator
97
    ): AbstractApiResponse
98
    {
99
        /** @var AbstractFormType $formData */
100 4
        $formData = $form->getData();
101 4
        $entityClass = $formData->getEntityClassName();
102
103 4
        $entity = $this->entityService->createEntityByFormData($formData, $creator, $entityClass);
104
105 4
        if (method_exists($entity, 'getId')) {
106 2
            $location = $this->createEntityHttpLocation($entity);
107 2
            $response = new CreatedApiResponse($location);
108
        } else {
109 2
            $response = new EmptyApiResponse(Response::HTTP_CREATED);
110
        }
111
112 4
        return $response;
113
    }
114
115
    /**
116
     * @param object $entity Entity
117
     * @param string $id Entity id
0 ignored issues
show
Bug introduced by
There is no parameter named $id. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
118
     * @return string
119
     */
120 2
    private function createEntityHttpLocation($entity): string
121
    {
122 2
        if (method_exists($entity, 'getId')) {
123 2
            $id = $entity->getId();
124
        } else {
125
            throw new MethodNotImplemented('getId');
126
        }
127
128 2
        $entityShortName = (new \ReflectionClass($entity))->getShortName();
129 2
        $route = strtolower($entityShortName) . '_view';
130
131 2
        return $this->router->generate($route, ['id' => $id], Router::ABSOLUTE_URL);
132
    }
133
}
134