Passed
Push — master ( 447a4c...2f567c )
by Julito
09:40
created

ExerciseCategoryManager   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 254
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 107
c 1
b 0
f 1
dl 0
loc 254
rs 10
wmc 15

9 Methods

Rating   Name   Duplication   Size   Complexity  
A getCategories() 0 9 1
A getJqgridActionLinks() 0 27 1
A return_form() 0 43 4
A __construct() 0 5 1
A display() 0 24 1
A getCourseCount() 0 9 1
A delete() 0 16 2
A save() 0 29 1
A getCategoriesForSelect() 0 13 3
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CourseBundle\Entity\CExerciseCategory;
5
6
/**
7
 * Class ExtraFieldValue
8
 * Declaration for the ExtraFieldValue class, managing the values in extra
9
 * fields for any data type.
10
 *
11
 * @package chamilo.library
12
 */
13
class ExerciseCategoryManager extends Model
14
{
15
    public $type = '';
16
    public $columns = [
17
        'id',
18
        'name',
19
        'c_id',
20
        'description',
21
        'created_at',
22
        'updated_at',
23
    ];
24
25
    /**
26
     * Formats the necessary elements for the given datatype.
27
     *
28
     * @param string $type The type of data to which this extra field
29
     *                     applies (user, course, session, ...)
30
     *
31
     * @assert (-1) === false
32
     */
33
    public function __construct()
34
    {
35
        parent::__construct();
36
        $this->is_course_model = true;
37
        $this->table = Database::get_course_table('exercise_category');
38
    }
39
40
    /**
41
     * Gets the number of values stored in the table (all fields together)
42
     * for this type of resource.
43
     *
44
     * @param int $courseId
45
     *
46
     * @return int Number of rows in the table
47
     */
48
    public function getCourseCount($courseId)
49
    {
50
        $em = Database::getManager();
51
        $query = $em->getRepository('ChamiloCourseBundle:CExerciseCategory')->createQueryBuilder('e');
52
        $query->select('count(e.id)');
53
        $query->where('e.cId = :cId');
54
        $query->setParameter('cId', $courseId);
55
56
        return $query->getQuery()->getSingleScalarResult();
57
    }
58
59
    /**
60
     * @param int $courseId
61
     *
62
     * @return array
63
     */
64
    public function getCategories($courseId)
65
    {
66
        $em = Database::getManager();
67
        $query = $em->getRepository('ChamiloCourseBundle:CExerciseCategory')->createQueryBuilder('e');
68
        $query->where('e.cId = :cId');
69
        $query->setParameter('cId', $courseId);
70
        $query->orderBy('e.position');
71
72
        return $query->getQuery()->getResult();
73
    }
74
75
    /**
76
     * @param int $courseId
77
     *
78
     * @return array
79
     */
80
    public function getCategoriesForSelect($courseId)
81
    {
82
        $categories = $this->getCategories($courseId);
83
        $options = [];
84
85
        if (!empty($categories)) {
86
            /** @var CExerciseCategory $category */
87
            foreach ($categories as $category) {
88
                $options[$category->getId()] = $category->getName();
89
            }
90
        }
91
92
        return $options;
93
    }
94
95
    /**
96
     * @param int $id
97
     */
98
    public function delete($id)
99
    {
100
        $em = Database::getManager();
101
        $repo = Database::getManager()->getRepository('ChamiloCourseBundle:CExerciseCategory');
102
        $category = $repo->find($id);
103
        if ($category) {
104
            $em->remove($category);
105
            $em->flush();
106
107
            $courseId = api_get_course_int_id();
108
            $table = Database::get_course_table(TABLE_QUIZ_TEST);
109
            $id = (int) $id;
110
111
            $sql = "UPDATE $table SET exercise_category_id = 0 
112
                    WHERE c_id = $courseId AND exercise_category_id = $id";
113
            Database::query($sql);
114
        }
115
    }
116
117
    /**
118
     * Save values in the *_field_values table.
119
     *
120
     * @param array $params    Structured array with the values to save
121
     * @param bool  $showQuery Whether to show the insert query (passed to the parent save() method)
122
     */
123
    public function save($params, $showQuery = false)
124
    {
125
        $courseId = api_get_course_int_id();
126
        $em = Database::getManager();
127
        $category = new CExerciseCategory();
128
        $category
129
            ->setName($params['name'])
130
            ->setCId(api_get_course_int_id())
131
            ->setDescription($params['name'])
132
        ;
133
        /*
134
            // Update position
135
            $query = $em->getRepository('ChamiloCourseBundle:CExerciseCategory')->createQueryBuilder('e');
136
            $query
137
                ->where('e.cId = :cId')
138
                ->setParameter('cId', $courseId)
139
                ->setMaxResults(1)
140
                ->orderBy('e.position', 'DESC');
141
            $last = $query->getQuery()->getOneOrNullResult();
142
            $position = 0;
143
            if (!empty($last)) {
144
                $position = $last->getPosition() + 1;
145
            }
146
            $category->setPosition($position);
147
*/
148
        $em->persist($category);
149
        $em->flush();
150
151
        return $category;
152
    }
153
154
    /**
155
     * @param $token
156
     *
157
     * @return string
158
     */
159
    public function getJqgridActionLinks($token)
160
    {
161
        //With this function we can add actions to the jgrid (edit, delete, etc)
162
        $editIcon = Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL);
163
        $deleteIcon = Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL);
164
        $confirmMessage = addslashes(
165
            api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES)
166
        );
167
168
        $courseParams = api_get_cidreq();
169
170
        $editButton = <<<JAVASCRIPT
171
            <a href="?action=edit&{$courseParams}&id=' + options.rowId + '" class="btn btn-link btn-xs">\
172
                $editIcon\
173
            </a>
174
JAVASCRIPT;
175
        $deleteButton = <<<JAVASCRIPT
176
            <a \
177
                onclick="if (!confirm(\'$confirmMessage\')) {return false;}" \
178
                href="?sec_token=$token&{$courseParams}&id=' + options.rowId + '&action=delete" \
179
                class="btn btn-link btn-xs">\
180
                $deleteIcon\
181
            </a>
182
JAVASCRIPT;
183
184
        return "function action_formatter(cellvalue, options, rowObject) {        
185
            return '$editButton $deleteButton';
186
        }";
187
    }
188
189
    /**
190
     * @param string $url
191
     * @param string $action
192
     *
193
     * @return FormValidator
194
     */
195
    public function return_form($url, $action)
196
    {
197
        $form = new FormValidator('category', 'post', $url);
198
        $id = isset($_GET['id']) ? (int) $_GET['id'] : null;
199
        $form->addElement('hidden', 'id', $id);
200
201
        // Setting the form elements
202
        $header = get_lang('Add');
203
        $defaults = [];
204
205
        if ($action === 'edit') {
206
            $header = get_lang('Modify');
207
            // Setting the defaults
208
            $defaults = $this->get($id, false);
209
        }
210
211
        $form->addElement('header', $header);
212
213
        $form->addText(
214
            'name',
215
            get_lang('Name')
216
        );
217
218
        $form->addHtmlEditor('description', get_lang('Description'));
219
220
        if ($action === 'edit') {
221
            $form->addButtonUpdate(get_lang('Modify'));
222
        } else {
223
            $form->addButtonCreate(get_lang('Add'));
224
        }
225
226
        /*if (!empty($defaults['created_at'])) {
227
            $defaults['created_at'] = api_convert_and_format_date($defaults['created_at']);
228
        }
229
        if (!empty($defaults['updated_at'])) {
230
            $defaults['updated_at'] = api_convert_and_format_date($defaults['updated_at']);
231
        }*/
232
        $form->setDefaults($defaults);
233
234
        // Setting the rules
235
        $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
236
237
        return $form;
238
    }
239
240
    /**
241
     * @return string
242
     */
243
    public function display()
244
    {
245
        // action links
246
        $content = '<div class="actions">';
247
        $content .= '<a href="'.api_get_path(WEB_CODE_PATH).'exercise/exercise.php?'.api_get_cidreq().'">';
248
        $content .= Display::return_icon(
249
            'back.png',
250
            get_lang('BackTo').' '.get_lang('PlatformAdmin'),
251
            '',
252
            ICON_SIZE_MEDIUM
253
        );
254
        $content .= '</a>';
255
        $content .= '<a href="'.api_get_self().'?action=add&'.api_get_cidreq().'">';
256
        $content .= Display::return_icon(
257
            'add.png',
258
            get_lang('Add'),
259
            '',
260
            ICON_SIZE_MEDIUM
261
        );
262
        $content .= '</a>';
263
        $content .= '</div>';
264
        $content .= Display::grid_html('categories');
265
266
        return $content;
267
    }
268
}
269