Passed
Push — master ( a751e7...ce04e2 )
by Petr
04:08
created

ApiResponseFactory::createEntityHttpLocation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 2
crap 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\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, $entity->getId());
0 ignored issues
show
Bug introduced by
The method getId does only exist in AppBundle\Entity\Infrasctucture\Ambassador, but not in AppBundle\Entity\Infrasctucture\AmbassadorMember.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
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
118
     * @return string
119
     */
120 2
    private function createEntityHttpLocation($entity, string $id): string
121
    {
122 2
        $entityShortName = (new \ReflectionClass($entity))->getShortName();
123 2
        $route = strtolower($entityShortName) . '_view';
124
125 2
        return $this->router->generate($route, ['id' => $id], Router::ABSOLUTE_URL);
126
    }
127
}
128