Completed
Push — master ( b91f6a...b5447e )
by Nikola
05:09
created

DeleteController::delete()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 11
Code Lines 8

Duplication

Lines 11
Ratio 100 %

Code Coverage

Tests 4
CRAP Score 2.3149

Importance

Changes 0
Metric Value
dl 11
loc 11
ccs 4
cts 7
cp 0.5714
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 3
nop 1
crap 2.3149
1
<?php
2
/*
3
 * This file is part of the Exchange Rate Bundle, an RunOpenCode project.
4
 *
5
 * (c) 2017 RunOpenCode
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
namespace RunOpenCode\Bundle\ExchangeRate\Controller;
11
12
use RunOpenCode\Bundle\ExchangeRate\Security\AccessVoter;
13
use RunOpenCode\ExchangeRate\Contract\RateInterface;
14
use RunOpenCode\ExchangeRate\Contract\RepositoryInterface;
15
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
18
use Symfony\Component\Security\Csrf\CsrfToken;
19
20
/**
21
 * Class DeleteController
22
 *
23
 * @package RunOpenCode\Bundle\ExchangeRate\Controller
24
 */
25
class DeleteController extends Controller
26
{
27
    /**
28
     * Main controller action
29
     *
30
     * @param Request $request
31
     * @return \Symfony\Component\HttpFoundation\Response
32
     */
33 2
    public function indexAction(Request $request)
34
    {
35 2
        return $this->render('@ExchangeRate/delete.html.twig', [
36 2
            'rate' => $this->getRateFromRequest($request)
37
        ]);
38
    }
39
40
    /**
41
     * Execute delete action.
42
     *
43
     * @param Request $request
44
     *
45
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
46
     */
47 2
    public function deleteAction(Request $request)
48
    {
49 2
        if (!$this->isCsrfTokenValid($request->getRequestUri(), $request->get('_csrf_token'))) {
50
            throw new InvalidCsrfTokenException();
51
        }
52
53
        /**
54
         * @var \RunOpenCode\ExchangeRate\Contract\RateInterface $rate
55
         */
56 2
        $rate = $this->getRateFromRequest($request);
57
58 1
        if (!$this->delete($rate)) {
59
            return $this->indexAction($request);
60
        }
61
62 1
        return $this->redirectAfterSuccess();
63
    }
64
65
    /**
66
     * Get rate from request
67
     *
68
     * @param Request $request
69
     *
70
     * @return \RunOpenCode\ExchangeRate\Contract\RateInterface
71
     */
72 3
    protected function getRateFromRequest(Request $request)
73
    {
74 3
        $source = $request->get('source');
75 3
        $rateType = $request->get('rate_type');
76 3
        $currencyCode = $request->get('currency_code');
77 3
        $date = \DateTime::createFromFormat('Y-m-d', $request->get('date'));
78
79
        /**
80
         * @var RepositoryInterface $repository
81
         */
82 3
        $repository = $this->get('runopencode.exchange_rate.repository');
83
84 3
        if (!$repository->has($source, $currencyCode, $date, $rateType)) {
0 ignored issues
show
Security Bug introduced by
It seems like $date defined by \DateTime::createFromFor... $request->get('date')) on line 77 can also be of type false; however, RunOpenCode\ExchangeRate...ositoryInterface::has() does only seem to accept null|object<DateTime>, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
85
            throw $this->createNotFoundException();
86
        }
87
88 3
        $rate = $repository->get($source, $currencyCode, $date, $rateType);
0 ignored issues
show
Security Bug introduced by
It seems like $date defined by \DateTime::createFromFor... $request->get('date')) on line 77 can also be of type false; however, RunOpenCode\ExchangeRate...ositoryInterface::get() does only seem to accept null|object<DateTime>, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
89
90 3
        if (!$this->isGranted(AccessVoter::DELETE, $rate)) {
91 2
            throw $this->createAccessDeniedException();
92
        }
93
94 1
        return $rate;
95
    }
96
97
    /**
98
     * Save rate.
99
     *
100
     * @param RateInterface $rate
101
     *
102
     * @return TRUE if successful.
103
     */
104 1 View Code Duplication
    protected function delete(RateInterface $rate)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
105
    {
106
        try {
107 1
            $this->get('runopencode.exchange_rate.repository')->delete([$rate]);
108 1
            $this->addFlash('success', $this->get('translator')->trans('flash.delete.success', [], 'runopencode_exchange_rate'));
109 1
            return true;
110
        } catch (\Exception $e) {
111
            $this->addFlash('error', $this->get('translator')->trans('flash.delete.error.unknown', [], 'runopencode_exchange_rate'));
112
            return false;
113
        }
114
    }
115
116
    /**
117
     * Redirect after success.
118
     *
119
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
120
     */
121 1
    protected function redirectAfterSuccess()
122
    {
123 1
        return $this->redirectToRoute('runopencode_exchange_rate_list');
124
    }
125
126
    /**
127
     * Check if CSRF token is valid, only if CSRF protection is enabled.
128
     *
129
     * @param string $id Intention.
130
     * @param string $token A token.
131
     *
132
     * @return bool TRUE if token is valid.
133
     */
134 2
    protected function isCsrfTokenValid($id, $token)
135
    {
136 2
        if (!$this->container->has('security.csrf.token_manager') && null !== $token) {
137
            throw new \LogicException('CSRF protection is not enabled in your application.');
138
        }
139
140 2
        return null !== $token ? $this->container->get('security.csrf.token_manager')->isTokenValid(new CsrfToken($id, $token)) : true;
141
    }
142
}
143