Completed
Push — master ( b8b518...903aaa )
by Laurent
03:24
created

OrdersController::updateAction()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 24
rs 8.9713
cc 2
eloc 15
nc 2
nop 2
1
<?php
2
/**
3
 * OrdersController controller des commandes.
4
 *
5
 * PHP Version 5
6
 *
7
 * @author    Quétier Laurent <[email protected]>
8
 * @copyright 2014 Dev-Int GLSR
9
 * @license   http://opensource.org/licenses/gpl-license.php GNU Public License
10
 *
11
 * @version since 1.0.0
12
 *
13
 * @link      https://github.com/Dev-Int/glsr
14
 */
15
namespace AppBundle\Controller;
16
17
use Symfony\Component\HttpFoundation\Request;
18
use AppBundle\Controller\AbstractOrdersController;
19
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
20
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
21
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
22
23
use AppBundle\Entity\Orders;
24
use AppBundle\Entity\Supplier;
25
use AppBundle\Form\Type\OrdersType;
26
use AppBundle\Form\Type\OrdersEditType;
27
use AppBundle\Entity\OrdersArticles;
28
29
/**
30
 * Orders controller.
31
 *
32
 * @Route("/orders")
33
 */
34
class OrdersController extends AbstractOrdersController
35
{
36
    /**
37
     * Lists all Orders entities.
38
     *
39
     * @Route("/", name="orders")
40
     * @Method("GET")
41
     * @Template()
42
     */
43 View Code Duplication
    public function indexAction(Request $request)
1 ignored issue
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...
44
    {
45
        $em = $this->getDoctrine()->getManager();
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $em. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
46
        $item = $this->container->getParameter('knp_paginator.page_range');
47
        $qb = $em->getRepository('AppBundle:Orders')->createQueryBuilder('o');
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $qb. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
48
        $qb->where('o.orderdate < ' . date('Y-m-d'));
49
        
50
        $createForm = $this->createCreateForm('orders_create');
51
52
        $paginator = $this->get('knp_paginator')->paginate($qb, $request->query->get('page', 1), $item);
53
        return array(
54
            'create_form' => $createForm->createView(),
55
            'paginator' => $paginator,
56
        );
57
    }
58
59
    /**
60
     * Finds and displays a Orders entity.
61
     *
62
     * @Route("/{id}/show", name="orders_show", requirements={"id"="\d+"})
63
     * @Method("GET")
64
     * @Template()
65
     */
66
    public function showAction(Orders $orders)
67
    {
68
        $deleteForm = $this->createDeleteForm($orders->getId(), 'orders_delete');
69
70
        return array(
71
            'orders' => $orders,
72
            'delete_form' => $deleteForm->createView(),
73
        );
74
    }
75
76
    /**
77
     * Displays a form to create a new Orders entity.
78
     *
79
     * @Route("/new/{supplier}", name="orders_new")
80
     * @Method("GET")
81
     * @Template()
82
     */
83
    public function newAction(Supplier $supplier)
84
    {
85
        $etm = $this->getDoctrine()->getManager();
86
87
        $orders = new Orders();
88
        $orders->setSupplier($supplier);
89
        $articles = $etm->getRepository('AppBundle:Article')->getArticleFromSupplier($supplier->getId());
90
91
        // Set Orders dates (order and delivery)
92
        $orders = $this->setDates($orders, $supplier);
93
94
        $etm->persist($orders);
95
        // Saving articles of supplier in order
96
        $this->saveOrdersArticles($articles, $orders, $etm);
97
98
        $etm->flush();
99
100
        return $this->redirect($this->generateUrl('orders_edit', array('id' => $orders->getId())));
101
    }
102
103
    /**
104
     * Creates a new Orders entity.
105
     *
106
     * @Route("/admin/create", name="orders_create")
107
     * @Method("POST")
108
     * @Template("AppBundle:Orders:new.html.twig")
109
     */
110
    public function createAction(Request $request)
111
    {
112
        $etm = $this->getDoctrine()->getManager();
113
114
        $orders = new Orders();
115
        $form = $this->createForm(OrdersType::class, $orders);
116
        $return = ['orders' => $orders, 'form' => $form->createView(),];
117
        $form->handleRequest($request);
118
        $supplier = $orders->getSupplier();
119
        $articles = $etm->getRepository('AppBundle:Article')->getArticleFromSupplier($supplier->getId());
120
        // Tester la liste si un fournisseur à déjà une commande en cours
121
        $test = $this->get('app.helper.controller')->testSupplierHasArticle($articles);
122
        if ($test === false) {
123
            $return = $this->redirectToRoute('orders');
124
        } else {
125
            // Set Orders dates (order and delivery)
126
            $orders = $this->setDates($orders, $supplier);
127
128
            if ($form->isValid() && $return !== $this->redirectToRoute('orders')) {
129
                $etm->persist($orders);
130
                // Saving articles of supplier in order
131
                $this->saveOrdersArticles($articles, $orders, $etm);
132
133
                $etm->flush();
134
135
                $return = $this->redirect($this->generateUrl('orders_edit', array('id' => $orders->getId())));
136
            }
137
        }
138
        return $return;
139
    }
140
141
    /**
142
     * Displays a form to edit an existing Orders entity.
143
     *
144
     * @Route("/admin/{id}/edit", name="orders_edit", requirements={"id"="\d+"})
145
     * @Method("GET")
146
     * @Template()
147
     */
148
    public function editAction(Orders $orders)
149
    {
150
        $editForm = $this->createForm(OrdersEditType::class, $orders, array(
151
            'action' => $this->generateUrl('orders_update', array('id' => $orders->getId())),
152
            'method' => 'PUT',
153
        ));
154
        $deleteForm = $this->createDeleteForm($orders->getId(), 'orders_delete');
155
156
        return array(
157
            'orders' => $orders,
158
            'edit_form'   => $editForm->createView(),
159
            'delete_form' => $deleteForm->createView(),
160
        );
161
    }
162
163
    /**
164
     * Edits an existing Orders entity.
165
     *
166
     * @Route("/admin/{id}/update", name="orders_update", requirements={"id"="\d+"})
167
     * @Method("PUT")
168
     * @Template("AppBundle:Orders:edit.html.twig")
169
     */
170
    public function updateAction(Orders $orders, Request $request)
171
    {
172
        $editForm = $this->createForm(OrdersEditType::class, $orders, array(
173
            'action' => $this->generateUrl('orders_update', array('id' => $orders->getId())),
174
            'method' => 'PUT',
175
        ));
176
        $deleteForm = $this->createDeleteForm($orders->getId(), 'orders_delete');
177
        $editForm->handleRequest($request);
178
179
        $return = array(
180
            'orders' => $orders,
181
            'edit_form'   => $editForm->createView(),
182
            'delete_form' => $deleteForm->createView(),
183
        );
184
        
185
        if ($editForm->isValid()) {
186
            $this->getDoctrine()->getManager()->flush();
187
            $this->addFlash('info', 'gestock.edit.ok');
188
189
            $return = $this->redirect($this->generateUrl('orders_edit', ['id' => $orders->getId()]));
190
        }
191
192
        return $return;
193
    }
194
195
    /**
196
     * Deletes a Orders entity.
197
     *
198
     * @Route("/admin/{id}/delete", name="orders_delete", requirements={"id"="\d+"})
199
     * @Method("DELETE")
200
     */
201
    public function deleteAction(Orders $orders, Request $request)
202
    {
203
        $etm = $this->getDoctrine()->getManager();
204
        $form = $this->createDeleteForm($orders->getId(), 'orders_delete');
205
        $ordersArticles = $etm->getRepository('AppBundle:OrdersArticles')->findByOrders($orders->getId());
0 ignored issues
show
Bug introduced by
The method findByOrders() does not exist on Doctrine\Common\Persistence\ObjectRepository. Did you maybe mean findBy()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
206
207
        if ($form->handleRequest($request)->isValid()) {
208
            foreach ($ordersArticles as $order) {
209
                $etm->remove($order);
210
            }
211
            $etm->remove($orders);
212
            $etm->flush();
213
        }
214
215
        return $this->redirect($this->generateUrl('orders'));
216
    }
217
218
    /**
219
     * Set order Dates.
220
     *
221
     * @param \AppBundle\Entity\Orders   $orders   La commande à traiter
222
     * @param \AppBundle\Entity\Supplier $supplier Le fournisseur concerné
223
     * @return \AppBundle\Entity\Orders            La commande modifiée
224
     */
225
    private function setDates(Orders $orders, Supplier $supplier)
226
    {
227
        $orderDate = $supplier->getOrderdate();
228
        foreach ($orderDate as $date) {
229
            if ($date >= date('w')) {
230
                $diffOrder = $date - date('w');
231
                $diffDeliv = $diffOrder + $supplier->getDelaydeliv();
232
                $dateOrder = date('Y-m-d H:i:s', mktime(0, 0, 0, date('n'), date('j')+$diffOrder, date('Y')));
233
                $delivDate = date('Y-m-d H:i:s', mktime(0, 0, 0, date('n'), date('j')+$diffDeliv, date('Y')));
234
                $orders->setOrderDate(\DateTime::createFromFormat('Y-m-d H:i:s', $dateOrder));
0 ignored issues
show
Security Bug introduced by
It seems like \DateTime::createFromFor...m-d H:i:s', $dateOrder) targeting DateTime::createFromFormat() can also be of type false; however, AppBundle\Entity\Orders::setOrderdate() does only seem to accept object<DateTime>, did you maybe forget to handle an error condition?
Loading history...
235
                $orders->setDelivDate(\DateTime::createFromFormat('Y-m-d H:i:s', $delivDate));
0 ignored issues
show
Security Bug introduced by
It seems like \DateTime::createFromFor...m-d H:i:s', $delivDate) targeting DateTime::createFromFormat() can also be of type false; however, AppBundle\Entity\Orders::setDelivdate() does only seem to accept object<DateTime>, did you maybe forget to handle an error condition?
Loading history...
236
                break;
237
            }
238
        }
239
        return $orders;
240
    }
241
242
    /**
243
     * Save OrdersArticles.
244
     *
245
     * @param array                      $articles Liste des articles
246
     * @param \AppBundle\Entity\Orders   $orders   La commande à traiter
247
     * @param \Doctrine\Common\Persistence\ObjectManager $etm Entity Manager
248
     */
249
    private function saveOrdersArticles($articles, $orders, $etm)
250
    {
251 View Code Duplication
        foreach ($articles as $article) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across 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...
252
            $ordersArticles = new OrdersArticles();
253
            $ordersArticles->setOrders($orders);
254
            $ordersArticles->setArticle($article);
255
            $ordersArticles->setUnitStorage($article->getUnitStorage());
256
            if ($article->getMinstock() > $article->getQuantity()) {
257
                $ordersArticles->setQuantity($article->getMinstock() - $article->getQuantity());
258
            }
259
            $ordersArticles->setPrice($article->getPrice());
260
            $ordersArticles->setTva($article->getTva());
261
            $etm->persist($ordersArticles);
262
        }
263
    }
264
265
    /**
266
     * Print the current order.<br />Creating a `PDF` file for viewing on paper
267
     *
268
     * @Route("/{id}/print/", name="orders_print", requirements={"id"="\d+"})
269
     * @Method("GET")
270
     * @Template()
271
     *
272
     * @param \AppBundle\Entity\Orders $orders Order item to print
273
     * @return \Symfony\Component\HttpFoundation\Response
274
     */
275
    public function printAction(Orders $orders)
276
    {
277
        $return = $this->abstractPrintAction($orders, 'Orders');
278
        
279
        return $return;
280
//        $file = 'order-' . $orders->getId() . '.pdf';
0 ignored issues
show
Unused Code Comprehensibility introduced by
52% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
281
//        $company = $this->getDoctrine()->getManager()->getRepository('AppBundle:Company')->find(1);
282
//        // Create and save the PDF file to print
283
//        $html = $this->renderView(
284
//            'AppBundle:Orders:print.pdf.twig',
285
//            ['articles' => $orders->getArticles(), 'orders' => $orders, 'company' => $company, ]
286
//        );
287
//        return new Response(
288
//            $this->get('knp_snappy.pdf')->getOutputFromHtml(
289
//                $html,
290
//                $this->getArray((string)date('d/m/y - H:i:s'), '')
291
//            ),
292
//            200,
293
//            array(
294
//                'Content-Type' => 'application/pdf',
295
//                'Content-Disposition' => 'attachment; filename="' . $file . '"'
296
//            )
297
//        );
298
    }
299
}
300