Completed
Push — master ( 6033c5...af0fd1 )
by Julito
10:22
created

ExerciseCategoryManager::getJqgridActionLinks()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 17
nc 1
nop 1
dl 0
loc 29
rs 9.7
c 1
b 0
f 1
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use APY\DataGridBundle\Grid\Action\MassAction;
5
use APY\DataGridBundle\Grid\Action\RowAction;
6
use APY\DataGridBundle\Grid\Row;
7
use APY\DataGridBundle\Grid\Source\Entity;
8
use Chamilo\CoreBundle\Entity\Resource\ResourceLink;
9
use Chamilo\CoreBundle\Framework\Container;
10
use Chamilo\CoreBundle\Security\Authorization\Voter\ResourceNodeVoter;
11
use Chamilo\CourseBundle\Entity\CExerciseCategory;
12
13
/**
14
 * Class ExtraFieldValue
15
 * Declaration for the ExtraFieldValue class, managing the values in extra
16
 * fields for any data type.
17
 */
18
class ExerciseCategoryManager extends Model
19
{
20
    public $type = '';
21
    public $columns = [
22
        'id',
23
        'name',
24
        'c_id',
25
        'description',
26
        'created_at',
27
        'updated_at',
28
    ];
29
30
    /**
31
     * Formats the necessary elements for the given datatype.
32
     *
33
     * @param string $type The type of data to which this extra field
34
     *                     applies (user, course, session, ...)
35
     *
36
     * @assert (-1) === false
37
     */
38
    public function __construct()
39
    {
40
        parent::__construct();
41
        $this->is_course_model = true;
42
        $this->table = Database::get_course_table('exercise_category');
43
    }
44
45
    /**
46
     * @param int $courseId
47
     *
48
     * @return array
49
     */
50
    public function getCategories($courseId)
51
    {
52
        return Container::getExerciseCategoryRepository()->getCategories($courseId);
53
    }
54
55
    /**
56
     * @param int $courseId
57
     *
58
     * @return array
59
     */
60
    public function getCategoriesForSelect($courseId)
61
    {
62
        $categories = $this->getCategories($courseId);
63
        $options = [];
64
65
        if (!empty($categories)) {
66
            /** @var CExerciseCategory $category */
67
            foreach ($categories as $category) {
68
                $options[$category->getId()] = $category->getName();
69
            }
70
        }
71
72
        return $options;
73
    }
74
75
    /**
76
     * @param int $id
77
     */
78
    public function delete($id)
79
    {
80
        $repo = Container::getExerciseCategoryRepository();
81
        $category = $repo->find($id);
82
        $repo->hardDelete($category);
0 ignored issues
show
Bug introduced by
It seems like $category can also be of type null; however, parameter $resource of Chamilo\CoreBundle\Repos...epository::hardDelete() does only seem to accept Chamilo\CoreBundle\Entit...source\AbstractResource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

82
        $repo->hardDelete(/** @scrutinizer ignore-type */ $category);
Loading history...
83
84
        return true;
85
    }
86
87
    /**
88
     * @param                                                   $primaryKeys
89
     * @param                                                   $allPrimaryKeys
90
     * @param \Symfony\Component\HttpFoundation\Session\Session $session
91
     * @param                                                   $parameters
92
     */
93
    public function deleteResource(
94
        $primaryKeys,
95
        $allPrimaryKeys,
0 ignored issues
show
Unused Code introduced by
The parameter $allPrimaryKeys is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

95
        /** @scrutinizer ignore-unused */ $allPrimaryKeys,

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
96
        Symfony\Component\HttpFoundation\Session\Session $session,
0 ignored issues
show
Unused Code introduced by
The parameter $session is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

96
        /** @scrutinizer ignore-unused */ Symfony\Component\HttpFoundation\Session\Session $session,

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
97
        $parameters
0 ignored issues
show
Unused Code introduced by
The parameter $parameters is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

97
        /** @scrutinizer ignore-unused */ $parameters

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
98
    ) {
99
        $repo = Container::getExerciseCategoryRepository();
100
        $translator = Container::getTranslator();
101
        foreach ($primaryKeys as $id) {
102
            $category = $repo->find($id);
103
            $repo->hardDelete($category);
0 ignored issues
show
Bug introduced by
It seems like $category can also be of type null; however, parameter $resource of Chamilo\CoreBundle\Repos...epository::hardDelete() does only seem to accept Chamilo\CoreBundle\Entit...source\AbstractResource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

103
            $repo->hardDelete(/** @scrutinizer ignore-type */ $category);
Loading history...
104
        }
105
106
        Display::addFlash(Display::return_message($translator->trans('Deleted')));
107
        header('Location:'.api_get_self().'?'.api_get_cidreq());
108
        exit;
109
    }
110
111
    /**
112
     * @param array $params
113
     * @param bool  $showQuery
114
     *
115
     * @return bool
116
     */
117
    public function update($params, $showQuery = false)
118
    {
119
        $id = $params['id'];
120
121
        $repo = Container::getExerciseCategoryRepository();
122
        /** @var CExerciseCategory $category */
123
        $category = $repo->find($id);
124
125
        if ($category) {
0 ignored issues
show
introduced by
$category is of type Chamilo\CourseBundle\Entity\CExerciseCategory, thus it always evaluated to true.
Loading history...
126
            $category
127
                ->setName($params['name'])
128
                ->setDescription($params['description'])
129
            ;
130
131
            $repo->getEntityManager()->persist($category);
132
            $repo->getEntityManager()->flush();
133
134
            return true;
135
        }
136
137
        return false;
138
    }
139
140
    /**
141
     * Save values in the *_field_values table.
142
     *
143
     * @param array $params    Structured array with the values to save
144
     * @param bool  $showQuery Whether to show the insert query (passed to the parent save() method)
145
     */
146
    public function save($params, $showQuery = false)
147
    {
148
        $courseId = api_get_course_int_id();
149
        $course = api_get_course_entity($courseId);
150
151
        $repo = Container::getExerciseCategoryRepository();
152
        $em = $repo->getEntityManager();
153
154
        $category = new CExerciseCategory();
155
        $category
156
            ->setName($params['name'])
157
            ->setCourse($course)
158
            ->setDescription($params['description'])
159
        ;
160
161
        /*
162
            // Update position
163
            $query = $em->getRepository('ChamiloCourseBundle:CExerciseCategory')->createQueryBuilder('e');
164
            $query
165
                ->where('e.cId = :cId')
166
                ->setParameter('cId', $courseId)
167
                ->setMaxResults(1)
168
                ->orderBy('e.position', 'DESC');
169
            $last = $query->getQuery()->getOneOrNullResult();
170
            $position = 0;
171
            if (!empty($last)) {
172
                $position = $last->getPosition() + 1;
173
            }
174
            $category->setPosition($position);
175
*/
176
        $em->persist($category);
177
178
        $repo->addResourceToCourse(
179
            $category,
180
            ResourceLink::VISIBILITY_PUBLISHED,
181
            api_get_user_entity(api_get_user_id()),
182
            $course,
183
            api_get_session_entity(),
184
            api_get_group_entity()
185
        );
186
187
        $em->flush();
188
189
        return $category;
190
    }
191
192
    /**
193
     * @param string $url
194
     * @param string $action
195
     *
196
     * @return FormValidator
197
     */
198
    public function return_form($url, $action)
199
    {
200
        $form = new FormValidator('category', 'post', $url);
201
        $id = isset($_GET['id']) ? (int) $_GET['id'] : null;
202
        $form->addElement('hidden', 'id', $id);
203
204
        // Setting the form elements
205
        $header = get_lang('Add');
206
        $defaults = [];
207
208
        if ($action === 'edit') {
209
            $header = get_lang('Edit');
210
            // Setting the defaults
211
            $defaults = $this->get($id, false);
212
        }
213
214
        $form->addElement('header', $header);
215
216
        $form->addText(
217
            'name',
218
            get_lang('Name')
219
        );
220
221
        $form->addHtmlEditor('description', get_lang('Description'));
222
223
        if ($action === 'edit') {
224
            $form->addButtonUpdate(get_lang('Edit'));
225
        } else {
226
            $form->addButtonCreate(get_lang('Add'));
227
        }
228
        $form->setDefaults($defaults);
229
230
        // Setting the rules
231
        $form->addRule('name', get_lang('Required field'), 'required');
232
233
        return $form;
234
    }
235
236
    /**
237
     * @return string
238
     */
239
    public function display()
240
    {
241
        $session = api_get_session_entity();
242
        $course = api_get_course_entity();
243
244
        // Action links
245
        $content = '<div class="actions">';
246
        $content .= '<a href="'.api_get_path(WEB_CODE_PATH).'exercise/exercise.php?'.api_get_cidreq().'">';
247
        $content .= Display::return_icon(
248
            'back.png',
249
            get_lang('Back to').' '.get_lang('Administration'),
250
            '',
251
            ICON_SIZE_MEDIUM
252
        );
253
        $content .= '</a>';
254
        $content .= '<a href="'.api_get_self().'?action=add&'.api_get_cidreq().'">';
255
        $content .= Display::return_icon(
256
            'add.png',
257
            get_lang('Add'),
258
            '',
259
            ICON_SIZE_MEDIUM
260
        );
261
        $content .= '</a>';
262
        $content .= '</div>';
263
264
        // 1. Set entity
265
        $source = new Entity('ChamiloCourseBundle:CExerciseCategory');
266
        $repo = Container::getExerciseCategoryRepository();
267
        // 2. Get query builder from repo.
268
        $qb = $repo->getResourcesByCourse($course, $session);
269
270
        // 3. Set QueryBuilder to the source.
271
        $source->initQueryBuilder($qb);
272
273
        // 4. Get the grid builder.
274
        $builder = Container::$container->get('apy_grid.factory');
275
276
        // 5. Set parameters and properties.
277
        $grid = $builder->createBuilder(
278
            'grid',
279
            $source,
280
            [
281
                'persistence' => false,
282
                'route' => 'home',
283
                'filterable' => true,
284
                'sortable' => true,
285
                'max_per_page' => 10,
286
            ]
287
        )->add(
288
            'id',
289
            'number',
290
            [
291
                'title' => '#',
292
                'primary' => true,
293
                'visible' => false,
294
            ]
295
        )->add(
296
            'name',
297
            'text',
298
            [
299
                'title' => get_lang('Name'),
300
            ]
301
        );
302
        $grid = $grid->getGrid();
303
304
        if (Container::getAuthorizationChecker()->isGranted(ResourceNodeVoter::ROLE_CURRENT_COURSE_TEACHER)) {
305
            // Add row actions
306
            $myRowAction = new RowAction(
307
                get_lang('Edit'),
308
                'legacy_main',
309
                false,
310
                '_self',
311
                ['class' => 'btn btn-secondary']
312
            );
313
            $myRowAction->setRouteParameters(
314
                ['id', 'name' => 'exercise/category.php', 'cidReq' => api_get_course_id(), 'action' => 'edit']
315
            );
316
317
            $myRowAction->addManipulateRender(
318
                function (RowAction $action, Row $row) use ($session, $repo) {
319
                    return $repo->rowCanBeEdited($action, $row, $session);
320
                }
321
            );
322
323
            $grid->addRowAction($myRowAction);
324
325
            $myRowAction = new RowAction(
326
                get_lang('Delete'),
327
                'legacy_main',
328
                true,
329
                '_self',
330
                ['class' => 'btn btn-danger', 'form_delete' => true]
331
            );
332
            $myRowAction->setRouteParameters(
333
                ['id', 'name' => 'exercise/category.php', 'cidReq' => api_get_course_id(), 'action' => 'delete']
334
            );
335
            $myRowAction->addManipulateRender(
336
                function (RowAction $action, Row $row) use ($session, $repo) {
337
                    return $repo->rowCanBeEdited($action, $row, $session);
338
                }
339
            );
340
341
            $grid->addRowAction($myRowAction);
342
343
            if (empty($session)) {
344
                // Add mass actions
345
                $deleteMassAction = new MassAction(
346
                    'Delete',
347
                    ['ExerciseCategoryManager', 'deleteResource'],
348
                    true,
349
                    []
350
                );
351
                $grid->addMassAction($deleteMassAction);
352
            }
353
        }
354
355
        // 8. Set route and request
356
        $grid
357
            ->setRouteUrl(api_get_self().'?'.api_get_cidreq())
358
            ->handleRequest(Container::getRequest())
359
        ;
360
361
        $content .= Container::$container->get('twig')->render(
362
            '@ChamiloTheme/Resource/grid.html.twig',
363
            ['grid' => $grid]
364
        );
365
366
        return $content;
367
    }
368
}
369