Passed
Push — master ( bd2c5e...fe5f43 )
by Petr
03:48
created

ApiResponseFactory::createImageResponse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 1
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\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());
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...
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