Completed
Push — master ( b8ee64...bf1b53 )
by Nikola
04:04
created

ExchangeRateController   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 251
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 0%

Importance

Changes 8
Bugs 1 Features 1
Metric Value
wmc 26
c 8
b 1
f 1
lcom 1
cbo 8
dl 0
loc 251
ccs 0
cts 108
cp 0
rs 10

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
A indexAction() 0 15 1
B newAction() 0 33 4
B editAction() 0 24 3
A deleteAction() 0 15 2
A getNewRate() 0 7 1
A getRateFromRequest() 0 8 2
A getNewFormType() 0 4 1
A getEditFormType() 0 4 1
A getFilterFormType() 0 4 1
A getFilterForm() 0 8 1
A getListData() 0 8 3
B denyAccessUnlessGranted() 0 18 5
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\EditType;
13
use RunOpenCode\Bundle\ExchangeRate\Form\Type\FilterType;
14
use RunOpenCode\Bundle\ExchangeRate\Form\Type\NewType;
15
use RunOpenCode\ExchangeRate\Contract\RateInterface;
16
use RunOpenCode\ExchangeRate\Contract\RepositoryInterface;
17
use RunOpenCode\Bundle\ExchangeRate\Model\Rate;
18
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
19
use Symfony\Component\Form\Form;
20
use Symfony\Component\Form\FormError;
21
use Symfony\Component\HttpFoundation\Request;
22
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
23
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
24
25
/**
26
 * Class ExchangeRateController
27
 *
28
 * Default exchange rate controller.
29
 *
30
 * @package RunOpenCode\Bundle\ExchangeRate\Controller
31
 */
32
class ExchangeRateController extends Controller
33
{
34
    /**
35
     * @var RepositoryInterface
36
     */
37
    protected $repository;
38
39
    /**
40
     * @var string
41
     */
42
    protected $baseCurrency;
43
44
    /**
45
     * @var array
46
     */
47
    protected $settings;
48
49
    public function __construct(
50
        RepositoryInterface $repository,
51
        $baseCurrency,
52
        $settings
53
    ) {
54
        $this->repository = $repository;
55
        $this->baseCurrency = $baseCurrency;
56
        $this->settings = $settings;
57
    }
58
59
    /**
60
     * List rates.
61
     *
62
     * @return \Symfony\Component\HttpFoundation\Response
63
     */
64
    public function indexAction(Request $request)
65
    {
66
        $this->denyAccessUnlessGranted(array('ROLE_EXCHANGE_RATE_MANAGER', 'ROLE_EXCHANGE_RATE_LIST'));
67
68
        $filter = $this->getFilterForm($request);
69
70
        return $this->render($this->settings['list'], array(
71
            'base_template' => $this->settings['base_template'],
72
            'filter' => $filter->createView(),
73
            'rates' => $this->getListData($filter),
74
            'date_format' => $this->settings['date_format'],
75
            'time_format' => $this->settings['time_format'],
76
            'secure' => $this->settings['secure']
77
        ));
78
    }
79
80
    /**
81
     * Add new rate.
82
     *
83
     * @param Request $request
84
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
85
     */
86
    public function newAction(Request $request)
87
    {
88
        $this->denyAccessUnlessGranted(array('ROLE_EXCHANGE_RATE_MANAGER', 'ROLE_EXCHANGE_RATE_CREATE'));
89
90
        $form = $this->createForm($this->getNewFormType(), $this->getNewRate());
91
92
        $form->handleRequest($request);
93
94
        if ($form->isSubmitted() && $form->isValid()) {
95
96
            /**
97
             * @var RateInterface $rate
98
             */
99
            $rate = $form->getData();
100
101
            if ($this->repository->has($rate->getSourceName(), $rate->getCurrencyCode(), $rate->getDate(), $rate->getRateType())) {
102
                $form->addError(new FormError($this->get('translator')->trans('exchange_rate.form.error.new_exists', array(), 'roc_exchange_rate')));
103
            } else {
104
                $this->repository->save(array(
105
                    $form->getData()
106
                ));
107
108
                $this->get('session')->getFlashBag()->add('success', 'exchange_rate.flash.new.success');
109
                return $this->redirectToRoute('roc_exchange_rate_list');
110
            }
111
        }
112
113
        return $this->render($this->settings['new'], array(
114
            'base_template' => $this->settings['base_template'],
115
            'form' => $form->createView(),
116
            'secure' => $this->settings['secure']
117
        ));
118
    }
119
120
    /**
121
     * Edit rate.
122
     *
123
     * @param Request $request
124
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
125
     */
126
    public function editAction(Request $request)
127
    {
128
        $this->denyAccessUnlessGranted(array('ROLE_EXCHANGE_RATE_MANAGER', 'ROLE_EXCHANGE_RATE_EDIT'));
129
130
        $form = $this->createForm($this->getEditFormType(), $this->getRateFromRequest($request));
131
132
        $form->handleRequest($request);
133
134
        if ($form->isSubmitted() && $form->isValid()) {
135
136
            $this->repository->save(array(
137
                $form->getData()
138
            ));
139
140
            $this->get('session')->getFlashBag()->add('success', 'exchange_rate.flash.edit.success');
141
            return $this->redirectToRoute('roc_exchange_rate_list');
142
        }
143
144
        return $this->render($this->settings['edit'], array(
145
            'base_template' => $this->settings['base_template'],
146
            'form' => $form->createView(),
147
            'secure' => $this->settings['secure']
148
        ));
149
    }
150
151
    /**
152
     * Delete rate.
153
     *
154
     * @param Request $request
155
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
156
     */
157
    public function deleteAction(Request $request)
158
    {
159
        $this->denyAccessUnlessGranted(array('ROLE_EXCHANGE_RATE_MANAGER', 'ROLE_EXCHANGE_RATE_DELETE'));
160
161
        if (!$this->isCsrfTokenValid($request->getRequestUri(), $request->get('_csrf_token'))) {
162
            throw new InvalidCsrfTokenException;
163
        }
164
165
        $rate = $this->getRateFromRequest($request);
166
167
        $this->repository->delete(array($rate));
168
169
        $this->get('session')->getFlashBag()->add('success', 'exchange_rate.flash.delete.success');
170
        return $this->redirectToRoute('roc_exchange_rate_list');
171
    }
172
173
    /**
174
     * Get new rate object for new form.
175
     *
176
     * @return Rate
177
     */
178
    protected function getNewRate()
179
    {
180
        $rate = new Rate(null, null, $this->baseCurrency, null, null, $this->baseCurrency, null, null);
181
        $rate->setBaseCurrencyCode($this->baseCurrency);
182
183
        return $rate;
184
    }
185
186
    /**
187
     * Find rate based on values of request parameters.
188
     *
189
     * @param Request $request
190
     * @return static
191
     */
192
    protected function getRateFromRequest(Request $request)
193
    {
194
        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...
195
            throw new NotFoundHttpException();
196
        }
197
198
        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...
199
    }
200
201
    /**
202
     * Get FQCN of NewType form.
203
     *
204
     * @return string
205
     */
206
    protected function getNewFormType()
207
    {
208
        return NewType::class;
209
    }
210
211
    /**
212
     * Get FQCN of EditType form.
213
     *
214
     * @return string
215
     */
216
    protected function getEditFormType()
217
    {
218
        return EditType::class;
219
    }
220
221
    /**
222
     * Get FQCN of FilterType form.
223
     *
224
     * @return string
225
     */
226
    protected function getFilterFormType()
227
    {
228
        return FilterType::class;
229
    }
230
231
    /**
232
     * Get filter form
233
     *
234
     * @param Request $request
235
     * @return Form
236
     */
237
    protected function getFilterForm(Request $request)
238
    {
239
        $filter = $this->createForm($this->getFilterFormType());
240
241
        $filter->handleRequest($request);
242
243
        return $filter;
244
    }
245
246
    /**
247
     * Get list data. Process filters if submitted.
248
     *
249
     * @param Form $filter
250
     * @return \RunOpenCode\ExchangeRate\Contract\RateInterface[]
251
     */
252
    protected function getListData(Form $filter)
253
    {
254
        if ($filter->isSubmitted() && $filter->isValid()) {
255
            return $this->repository->all($filter->getData());
256
        }
257
258
        return $this->repository->all();
259
    }
260
261
    /**
262
     * {@inheritdoc}
263
     */
264
    protected function denyAccessUnlessGranted($attributes, $object = null, $message = 'Access Denied.')
265
    {
266
        if ($this->settings['secure']) {
267
            if (!is_array($attributes)) {
268
                $attributes = array($attributes);
269
            }
270
271
            $granted = false;
272
273
            foreach ($attributes as $attribute) {
274
                $granted |= $this->isGranted($attribute, $object);
275
            }
276
277
            if (!$granted) {
278
                throw $this->createAccessDeniedException($message);
279
            }
280
        }
281
    }
282
}
283