Completed
Push — master ( 2d0383...d13a60 )
by philippe
03:58
created

AdvertController::view()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 9
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace App\Controller;
4
5
use App\Entity\AdSearch;
6
use App\Entity\Advert;
7
use App\Entity\Category;
8
use App\Entity\Department;
9
use App\Form\AddAdvertType;
10
use App\Form\AdSearchType;
11
use App\Form\DepartmentType;
12
use App\Repository\AdvertRepository;
13
use Doctrine\Common\Persistence\ObjectManager;
14
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
15
use Symfony\Component\HttpFoundation\File\Exception\FileException;
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
18
use Symfony\Component\Routing\Annotation\Route;
19
use Knp\Component\Pager\PaginatorInterface;
20
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
21
22
class AdvertController extends AbstractController
23
{
24
    /**
25
     * @var AdvertRepository
26
     */
27
    private $repository;
28
    /**
29
     * @var ObjectManager
30
     */
31
    private $em;
32
33
    public function __construct(AdvertRepository $repository, ObjectManager $em)
34
    {
35
36
        $this->repository = $repository;
37
        $this->em = $em;
38
    }
39
40
    /**
41
     * @Route("/adverts", name="adverts")
42
     */
43
    public function index(Request $request, PaginatorInterface $paginator)
44
    {
45
46
        $search = new AdSearch();
47
        $form = $this->createForm(AdSearchType::class, $search);
48
        $form->handleRequest($request);
49
50
        //dump($form->getData(), $search);
51
            $adverts = $paginator->paginate(
52
                $queryBuilder = $this->repository->findAll(),
53
                $request->query->getInt('page', 1)/*page number*/,
54
                10/*limit per page*/
55
            );
56
57
        if ($form->isSubmitted() && $form->isValid()) {
58
            if ($search->getDepartment()) {
59
                $department = $request->query->get('department');
60
                $adverts = $paginator->paginate(
61
                    $queryBuilder = $this->repository->findAllVisibleQuery($department),
62
                    $request->query->getInt('page', 1)/*page number*/,
63
                    10/*limit per page*/
64
                );
65
            }
66
        }
67
68
69
        return $this->render('advert/index.html.twig', [
70
            'pagination' => $adverts,
71
            'formSearch' => $form->createView(),
72
        ]);
73
    }
74
75
    /**
76
     * @Route("/advert/add", name="add_advert")
77
     */
78
    public function add(Request $request, ObjectManager $manager)
79
    {
80
        $advert = new Advert();
81
        $form = $this->createForm(AddAdvertType::class, $advert);
82
        $form->handleRequest($request);
83
        if ($form->isSubmitted() && $form->isValid()) {
84
            $advert->setDate(new \DateTime());
85
            $advert->setAuthor($this->getUser());
86
87
            $manager->persist($advert);
88
            $manager->flush();
89
90
            $this->addFlash('success', 'Votre annonce a bien été ajoutée');
91
            return $this->redirectToRoute('advert', ['id' => $advert->getId()]);
92
        }
93
        return $this->render('advert/add.html.twig', [
94
            'formAddAdvert' => $form->createView(),
95
        ]);
96
    }
97
98
    /**
99
     * @Route("/advert/{id}", name="advert")
100
     */
101
    public function view($id)
102
    {
103
        $em = $this->getDoctrine()->getManager();
104
        $advert = $em->getRepository(Advert::class)->find($id);
105
        if (null == $advert) {
106
            throw new NotFoundHttpException("L'annonce d'id ".$id." n'existe pas");
107
        }
108
        return $this->render('advert/view.html.twig', [
109
            'advert' => $advert,
110
        ]);
111
    }
112
113
    /**
114
     * @Route("/advert/edit/{id}", name="edit_advert")
115
     *
116
     */
117
    public function edit(Advert $advert, Request $request, ObjectManager $manager)
118
    {
119
        //$advert = $this->getDoctrine()->getRepository(Advert::class)->find($id);
120
        if (null == $advert) {
121
            throw new NotFoundHttpException("Pas d\'annonce avec cet identifiant");
122
        }
123
        if ($advert->getAuthor() === $this->getUser()) {
124
            $form = $this->createForm(AddAdvertType::class, $advert);
125
            $form->handleRequest($request);
126
            if ($form->isSubmitted() && $form->isValid()) {
127
                $advert->setAuthor($this->getUser());
128
129
                $advert->setPublished(false);
130
131
                $categories = $advert->getCategories();
132
133
                // On boucle sur les catégories pour les lier à l'annonce
134
                foreach ($categories as $category) {
135
                    $advert->addCategory($category);
136
                }
137
138
                //$manager->persist($advert);
139
                $manager->flush();
140
                $this->addFlash(
141
                    'notice',
142
                    'L\'annonce a bien été modifiée! En attente de validation par l\'administrateur'
143
                );
144
                return $this->redirectToRoute('advert', ['id' => $advert->getId()]);
145
            }
146
            return $this->render('advert/edit.html.twig', [
147
                'advert' => $advert,
148
                'formEditAdvert' => $form->createView()
149
            ]);
150
        } else {
151
            $this->addFlash('warning', 'Vous devez être l\'auteur pour modifier cette annonce !');
152
            return $this->redirectToRoute('advert', ['id' => $advert->getId()]);
153
        }
154
    }
155
156
    /**
157
     * Supprimer une annonce
158
     *
159
     * @Route("/advert/delete/{id}", name="delete_advert")
160
     */
161
    public function deleteAction($id)
162
    {
163
        $em = $this->getDoctrine()->getManager();
164
        $advert = $em->getRepository(Advert::class)->find($id);
165
        if (null === $advert) {
166
            throw new NotFoundHttpException("L'annonce d'id ".$id." nexiste pas");
167
        }
168
        if ($advert->getAuthor() === $this->getUser()) {
169
            $em->remove($advert);
170
            $em->flush();
171
            $this->addFlash(
172
                'notice',
173
                'L\'annonce a bien été supprimée!'
174
            );
175
        } else {
176
            $this->addFlash('notice', 'Vous devez être l\'auteur pour supprimer cette annonce !');
177
            return $this->redirectToRoute('view', ['id' => $advert->getId()]);
178
        }
179
        return $this->redirectToRoute('home');
180
    }
181
}
182