Completed
Push — 2.0.0 ( 0d0c61...e99920 )
by John
04:25
created

ArticleView::editView()   C

Complexity

Conditions 7
Paths 64

Size

Total Lines 82
Code Lines 28

Duplication

Lines 4
Ratio 4.88 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 4
loc 82
rs 6.5492
cc 7
eloc 28
nc 64
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Alpha\View;
4
5
use Alpha\Util\Config\ConfigProvider;
6
use Alpha\Util\Extension\MarkdownFacade;
7
use Alpha\Util\Security\SecurityUtils;
8
use Alpha\View\Widget\Button;
9
use Alpha\Controller\Front\FrontController;
10
11
/**
12
 * The rendering class for the Article class.
13
 *
14
 * @since 1.0
15
 *
16
 * @author John Collins <[email protected]>
17
 * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
18
 * @copyright Copyright (c) 2015, John Collins (founder of Alpha Framework).
19
 * All rights reserved.
20
 *
21
 * <pre>
22
 * Redistribution and use in source and binary forms, with or
23
 * without modification, are permitted provided that the
24
 * following conditions are met:
25
 *
26
 * * Redistributions of source code must retain the above
27
 *   copyright notice, this list of conditions and the
28
 *   following disclaimer.
29
 * * Redistributions in binary form must reproduce the above
30
 *   copyright notice, this list of conditions and the
31
 *   following disclaimer in the documentation and/or other
32
 *   materials provided with the distribution.
33
 * * Neither the name of the Alpha Framework nor the names
34
 *   of its contributors may be used to endorse or promote
35
 *   products derived from this software without specific
36
 *   prior written permission.
37
 *
38
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
39
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
40
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
41
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
42
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
43
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
48
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
49
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
50
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
51
 * </pre>
52
 */
53
class ArticleView extends View
54
{
55
    /**
56
     * Method to generate the markdown HTML render of the article content.
57
     *
58
     * @param array $fields Hash array of HTML fields to pass to the template.
59
     *
60
     * @since 1.0
61
     *
62
     * @return string
63
     */
64
    public function markdownView($fields = array())
65
    {
66
        $config = ConfigProvider::getInstance();
0 ignored issues
show
Unused Code introduced by
$config is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
67
68
        $markdown = new MarkdownFacade($this->BO);
69
70
        $fields['markdownContent'] = $markdown->getContent();
71
72
        return $this->loadTemplate($this->BO, 'markdown', $fields);
73
    }
74
75
    /**
76
     * Adds a note to the create article screen.
77
     *
78
     * @return string
79
     *
80
     * @since 1.0
81
     */
82
    protected function after_createView_callback()
83
    {
84
        return '<p><strong>Please note</strong> that you will only be able to attach files to the article once it has been created.</p><br>';
85
    }
86
87
    /**
88
     * Renders the list view (adds the dateAdded field for the list template).
89
     *
90
     * @param array $fields hash array of HTML fields to pass to the template
91
     *
92
     * @since 1.0
93
     *
94
     * @return string
95
     */
96
    public function listView($fields = array())
97
    {
98
        $fields['dateAdded'] = $this->BO->getCreateTS()->getDate();
99
        $fields['editButtonURL'] = FrontController::generateSecureURL('act=Alpha\Controller\ArticleController&ActiveRecordType='.get_class($this->BO).'&ActiveRecordOID='.$this->BO->getOID().'&view=edit');
100
101
        return parent::listView($fields);
102
    }
103
104
    /**
105
     * Renders a form to enable article editing with attachments options.
106
     *
107
     * @param array $fields hash array of HTML fields to pass to the template
108
     *
109
     * @since 1.0
110
     *
111
     * @return string
112
     */
113
    public function editView($fields = array())
114
    {
115
        if (method_exists($this, 'before_editView_callback')) {
116
            $this->before_editView_callback();
0 ignored issues
show
Bug introduced by
The method before_editView_callback() does not exist on Alpha\View\ArticleView. Did you maybe mean editView()?

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...
117
        }
118
119
        $config = ConfigProvider::getInstance();
120
121
        // the form action
122
        if (isset($fields['URI'])) {
123
            $fields['formAction'] = $fields['URI'];
124
        }
125
126
        // the form ID
127
        $fields['formID'] = stripslashes(get_class($this->BO)).'_'.$this->BO->getID();
128
129
        // buffer form fields to $formFields
130
        $fields['formFields'] = $this->renderAllFields('edit');
131
132
        // buffer HTML output for Create and Cancel buttons
133
        $button = new Button('submit', 'Save', 'saveBut');
134
        $fields['saveButton'] = $button->render();
135
136
        $js = "if(window.jQuery) {
137
                    BootstrapDialog.show({
138
                        title: 'Confirmation',
139
                        message: 'Are you sure you wish to delete this item?',
140
                        buttons: [
141
                            {
142
                                icon: 'glyphicon glyphicon-remove',
143
                                label: 'Cancel',
144
                                cssClass: 'btn btn-default btn-xs',
145
                                action: function(dialogItself){
146
                                    dialogItself.close();
147
                                }
148
                            },
149
                            {
150
                                icon: 'glyphicon glyphicon-ok',
151
                                label: 'Okay',
152
                                cssClass: 'btn btn-default btn-xs',
153
                                action: function(dialogItself) {
154
                                    $('[id=\"".($config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('ActiveRecordOID')) : 'ActiveRecordOID')."\"]').attr('value', '".$this->BO->getOID()."');
155
                                    $('#deleteForm').submit();
156
                                    dialogItself.close();
157
                                }
158
                            }
159
                        ]
160
                    });
161
                }";
162
163
        $button = new Button($js, 'Delete', 'deleteBut');
164
        $fields['deleteButton'] = $button->render();
165
166
        $button = new Button("document.location = '".FrontController::generateSecureURL('act=Alpha\Controller\ActiveRecordController&ActiveRecordType='.get_class($this->BO).'&start=0&limit='.$config->get('app.list.page.amount'))."'", 'Back to List', 'cancelBut');
167
        $fields['cancelButton'] = $button->render();
168
169
        $tags = array();
170
171
        if (is_object($this->BO->getPropObject('tags'))) {
172
            $tags = $this->BO->getPropObject('tags')->getRelatedObjects();
173
        }
174
175 View Code Duplication
        if (count($tags) > 0) {
0 ignored issues
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...
176
            $button = new Button("document.location = '".FrontController::generateSecureURL('act=Alpha\Controller\TagController&ActiveRecordType='.get_class($this->BO).'&ActiveRecordOID='.$this->BO->getOID())."'", 'Edit Tags', 'tagsBut');
177
            $fields['tagsButton'] = $button->render();
178
        }
179
180
        // buffer security fields to $formSecurityFields variable
181
        $fields['formSecurityFields'] = $this->renderSecurityFields();
182
183
        // OID will need to be posted for optimistic lock checking
184
        $fields['version_num'] = $this->BO->getVersionNumber();
185
186
        // file attachments section
187
        $fields['fileAttachments'] = $this->renderFileUploadSection();
188
189
        if (method_exists($this, 'after_editView_callback')) {
190
            $this->after_editView_callback();
0 ignored issues
show
Bug introduced by
The method after_editView_callback() does not exist on Alpha\View\ArticleView. Did you maybe mean editView()?

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...
191
        }
192
193
        return $this->loadTemplate($this->BO, 'edit', $fields);
194
    }
195
196
    /**
197
     * Renders the HTML for the file upload section.
198
     *
199
     * @return string
200
     *
201
     * @since 1.0
202
     */
203
    protected function renderFileUploadSection()
204
    {
205
        $config = ConfigProvider::getInstance();
206
207
        $html = '<div class="form-group">';
208
        $html .= '  <h3>File Attachments:</h3>';
209
210
        if (is_dir($this->BO->getAttachmentsLocation())) {
211
            $handle = opendir($this->BO->getAttachmentsLocation());
212
213
            $fileCount = 0;
214
215
            $html .= '<table class="table table-bordered">';
216
217
            // loop over the attachments directory
218
            while (false !== ($file = readdir($handle))) {
219
                if ($file != '.' && $file != '..') {
220
                    ++$fileCount;
221
222
                    $html .= '<tr>';
223
224
                    $html .= '<td>'.$file.' <em>('.number_format(filesize($this->BO->getAttachmentsLocation().'/'.$file) / 1024).' KB)</em></td>';
225
226
                    $js = "if(window.jQuery) {
227
                            BootstrapDialog.show({
228
                                title: 'Confirmation',
229
                                message: 'Are you sure you wish to delete this item?',
230
                                buttons: [
231
                                    {
232
                                        icon: 'glyphicon glyphicon-remove',
233
                                        label: 'Cancel',
234
                                        cssClass: 'btn btn-default btn-xs',
235
                                        action: function(dialogItself){
236
                                            dialogItself.close();
237
                                        }
238
                                    },
239
                                    {
240
                                        icon: 'glyphicon glyphicon-ok',
241
                                        label: 'Okay',
242
                                        cssClass: 'btn btn-default btn-xs',
243
                                        action: function(dialogItself) {
244
                                            $('[id=\"".($config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('deletefile')) : 'deletefile')."\"]').attr('value', '".$file."');
245
                                            $('[id=\"".stripslashes(get_class($this->BO)).'_'.$this->BO->getID()."\"]').submit();
246
                                            dialogItself.close();
247
                                        }
248
                                    }
249
                                ]
250
                            });
251
                        }";
252
                    $button = new Button($js, 'Delete', 'delete'.$fileCount.'But');
253
                    $html .= '<td>'.$button->render().'</td>';
254
                    $html .= '</tr>';
255
                }
256
            }
257
258
            $html .= '</table>';
259
        } else {
260
            // we will take this opportunity to create the attachments folder is it does
261
            // not already exist.
262
            $this->BO->createAttachmentsFolder();
263
        }
264
265
        $html .= '<span class="btn btn-default btn-file">';
266
        $html .= '<input name="userfile" type="file" value="Browse..."/>';
267
        $html .= '</span>';
268
269
        $temp = new Button('submit', 'Upload', 'uploadBut');
270
        $html .= $temp->render();
271
272
        $fieldname = ($config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('deletefile')) : 'deletefile');
273
        $html .= '<input type="hidden" name="'.$fieldname.'" id="'.$fieldname.'" value=""/>';
274
275
        $html .= '</div>';
276
277
        return $html;
278
    }
279
}
280