Completed
Push — master ( 9ce938...bc87d6 )
by Nikola
07:13
created

ExchangeRateController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 9
ccs 0
cts 9
cp 0
rs 9.6667
cc 1
eloc 7
nc 1
nop 3
crap 2
1
<?php
2
/*
3
 * This file is part of the Exchange Rate Bundle, an RunOpenCode project.
4
 *
5
 * (c) 2016 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\Form\Type\NewType;
13
use RunOpenCode\ExchangeRate\Contract\RateInterface;
14
use RunOpenCode\ExchangeRate\Contract\RepositoryInterface;
15
use RunOpenCode\Bundle\ExchangeRate\Model\Rate;
16
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
17
use Symfony\Component\Form\FormError;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
20
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
21
22
/**
23
 * Class ExchangeRateController
24
 *
25
 * Default exchange rate controller.
26
 *
27
 * @package RunOpenCode\Bundle\ExchangeRate\Controller
28
 */
29
class ExchangeRateController extends Controller
30
{
31
    /**
32
     * @var RepositoryInterface
33
     */
34
    protected $repository;
35
36
    /**
37
     * @var string
38
     */
39
    protected $baseCurrency;
40
41
    /**
42
     * @var array
43
     */
44
    protected $settings;
45
46
    public function __construct(
47
        RepositoryInterface $repository,
48
        $baseCurrency,
49
        $settings
50
    ) {
51
        $this->repository = $repository;
52
        $this->baseCurrency = $baseCurrency;
53
        $this->settings = $settings;
54
    }
55
56
    /**
57
     * List rates.
58
     *
59
     * @return \Symfony\Component\HttpFoundation\Response
60
     */
61
    public function indexAction()
62
    {
63
        $this->denyAccessUnlessGranted(array('ROLE_EXCHANGE_RATE_MANAGER', 'ROLE_EXCHANGE_RATE_LIST'));
64
65
        return $this->render($this->settings['list'], array(
66
            'base_template' => $this->settings['base_template'],
67
            'rates' => $this->repository->all(),
68
            'date_format' => $this->settings['date_format'],
69
            'time_format' => $this->settings['time_format'],
70
            'secure' => $this->settings['secure']
71
        ));
72
    }
73
74
    /**
75
     * Add new rate.
76
     *
77
     * @param Request $request
78
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
79
     */
80
    public function newAction(Request $request)
81
    {
82
        $this->denyAccessUnlessGranted(array('ROLE_EXCHANGE_RATE_MANAGER', 'ROLE_EXCHANGE_RATE_CREATE'));
83
84
        $form = $this->createForm(NewType::class, $this->getNewRate());
85
86
        $form->handleRequest($request);
87
88
        if ($form->isSubmitted() && $form->isValid()) {
89
90
            /**
91
             * @var RateInterface $rate
92
             */
93
            $rate = $form->getData();
94
95
            if ($this->repository->has($rate->getCurrencyCode(), $rate->getDate(), $rate->getRateType())) {
0 ignored issues
show
Documentation introduced by
$rate->getDate() is of type object<DateTime>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
$rate->getRateType() is of type string, but the function expects a null|object<DateTime>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
96
                $form->addError(new FormError($this->get('translator')->trans('exchange_rate.form.error.new_exists', array(), 'roc_exchange_rate')));
97
            } else {
98
                $this->repository->save(array(
99
                    $form->getData()
100
                ));
101
102
                $this->get('session')->getFlashBag()->add('success', 'exchange_rate.flash.new.success');
103
                return $this->redirectToRoute('roc_exchange_rate_list');
104
            }
105
        }
106
107
        return $this->render($this->settings['new'], array(
108
            'base_template' => $this->settings['base_template'],
109
            'form' => $form->createView(),
110
            'secure' => $this->settings['secure']
111
        ));
112
    }
113
114
    /**
115
     * Edit rate.
116
     *
117
     * @param Request $request
118
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
119
     */
120
    public function editAction(Request $request)
121
    {
122
        $this->denyAccessUnlessGranted(array('ROLE_EXCHANGE_RATE_MANAGER', 'ROLE_EXCHANGE_RATE_EDIT'));
123
124
        $form = $this->createForm(NewType::class, $this->getRateFromRequest($request));
125
126
        $form->handleRequest($request);
127
128
        if ($form->isSubmitted() && $form->isValid()) {
129
130
            $this->repository->save(array(
131
                $form->getData()
132
            ));
133
134
            $this->get('session')->getFlashBag()->add('success', 'exchange_rate.flash.edit.success');
135
            return $this->redirectToRoute('roc_exchange_rate_list');
136
        }
137
138
        return $this->render($this->settings['edit'], array(
139
            'base_template' => $this->settings['base_template'],
140
            'form' => $form->createView(),
141
            'secure' => $this->settings['secure']
142
        ));
143
    }
144
145
    /**
146
     * Delete rate.
147
     *
148
     * @param Request $request
149
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
150
     */
151
    public function deleteAction(Request $request)
152
    {
153
        $this->denyAccessUnlessGranted(array('ROLE_EXCHANGE_RATE_MANAGER', 'ROLE_EXCHANGE_RATE_DELETE'));
154
155
        if (!$this->isCsrfTokenValid($request->getRequestUri(), $request->get('_csrf_token'))) {
156
            throw new InvalidCsrfTokenException;
157
        }
158
159
        $rate = $this->getRateFromRequest($request);
160
161
        $this->repository->delete(array($rate));
162
163
        $this->get('session')->getFlashBag()->add('success', 'exchange_rate.flash.delete.success');
164
        return $this->redirectToRoute('roc_exchange_rate_list');
165
    }
166
167
    /**
168
     * Get new rate object for new form.
169
     *
170
     * @return Rate
171
     */
172
    protected function getNewRate()
173
    {
174
        $rate = new Rate(null, null, $this->baseCurrency, null, null, $this->baseCurrency, null, null);
175
        $rate->setBaseCurrencyCode($this->baseCurrency);
176
177
        return $rate;
178
    }
179
180
    /**
181
     * Find rate based on values of request parameters.
182
     *
183
     * @param Request $request
184
     * @return static
185
     */
186
    protected function getRateFromRequest(Request $request)
187
    {
188
        if (!$this->repository->has($request->get('source'), $request->get('currency_code'), \DateTime::createFromFormat('Y-m-d', $request->get('date')), $request->get('rate_type'))) {
0 ignored issues
show
Security Bug introduced by
It seems like \DateTime::createFromFor... $request->get('date')) targeting DateTime::createFromFormat() 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?
Loading history...
189
            throw new NotFoundHttpException();
190
        }
191
192
        return Rate::fromRateInterface($this->repository->get($request->get('source'), $request->get('currency_code'), \DateTime::createFromFormat('Y-m-d', $request->get('date')), $request->get('rate_type')));
0 ignored issues
show
Security Bug introduced by
It seems like \DateTime::createFromFor... $request->get('date')) targeting DateTime::createFromFormat() 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?
Loading history...
193
    }
194
195
    /**
196
     * {@inheritdoc}
197
     */
198
    protected function denyAccessUnlessGranted($attributes, $object = null, $message = 'Access Denied.')
199
    {
200
        if ($this->settings['secure']) {
201
            if (!is_array($attributes)) {
202
                $attributes = array($attributes);
203
            }
204
205
            $granted = false;
206
207
            foreach ($attributes as $attribute) {
208
                $granted |= $this->isGranted($attribute, $object);
209
            }
210
211
            if (!$granted) {
212
                throw $this->createAccessDeniedException($message);
213
            }
214
        }
215
    }
216
}
217