Completed
Push — master ( 00ca69...f76e7b )
by Rasmus
01:56
created

ContentController::setupAction()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 108
Code Lines 80

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 108
ccs 0
cts 85
cp 0
rs 8.2857
c 0
b 0
f 0
cc 2
eloc 80
nc 2
nop 0
crap 6

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
namespace Chp\TextContent;
3
4 1
include_once(__DIR__ . '/../../app/config/text-content.php');
5
6
/**
7
 * Text content controller
8
 * Made by Rasmus Berg (c) 2014-2017
9
 *
10
 * @property  object  $di         Anax-MVC class handler
11
 * @property  object  $request    Anax-MVC $_POST, $_GET and $_SERVER handler class
12
 * @property  object  $response   Anax-MVC Php Header class
13
 * @property  object  $url        Anax-MVC url-handler class
14
 * @property  object  $theme      Anax-MVC theme-handler class
15
 * @property  object  $views      Anax-MVC views-handler class
16
 * @property  object  $textFilter Anax-MVC textformat-handler class
17
 * @property  object  $db         PDO database class
18
 */
19
class ContentController implements \Anax\DI\IInjectionAware
20
{
21
  use \Anax\DI\TInjectable;
22
  
23
  /**
24
	 * Properties
25
	 */
26
  private $content;
27
  private $valid;
28
  private $contentPerPage; // Limit contents on list page
29
  private $urlPrefix;
30
  private $miniLength;
31
  
32
  /**
33
   * Initialize the controller
34
   *
35
   * @return    void
36
   */
37 7
  public function initialize(){
38 7
    if(!is_object($this->di))
39 7
      throw new \Anax\Exception\InternalServerErrorException('"$this->di" is not valid!');
40
    
41 7
    $this->content = new \Chp\TextContent\Content();
42 7
    $this->content->setDI($this->di);
43 7
    $this->valid = new \Chp\TextContent\ValidContent();
44 7
    $this->valid->setDI($this->di);
45 7
    $this->valid->initialize();
46
    
47 7
    $this->contentPerPage = CHP_TC_CONTENTPERPAGE;
48 7
    $this->urlPrefix      = CHP_TC_URLPREFIX;
49 7
    $this->miniLength     = CHP_TC_MINILENGTH;
50 7
  }
51
  
52
  /**
53
	 * Index content - use listAction 
54
   *
55
	 * @return		void
56
	 */
57
	public function indexAction(){
58
    $this->listAction();
59
  }
60
  
61
  /**
62
   * Setup content (If it allready exist it will restore database to begining)
63
   *
64
   * @return    void
65
   */
66
  public function setupAction(){
67
    $toDo   = "Restore or setup";
68
    $toWhat = "content database tables";
69
    $title  = "{$toDo} {$toWhat}";
70
    $form   = $this->confirmForm($this->url->create("{$this->urlPrefix}content/"));
71
    $status = $form->check();
72
73
    if($status === true){
74
    
75
      $this->db->dropTableIfExists('content')->execute();
76
77
      $this->db->createTable(
78
        'content',
79
        [
80
          'id'        => ['integer', 'primary key', 'not null', 'auto_increment'],
81
          'slug'      => ['char(80)'],
82
          'url'       => ['char(80)'],
83
          'type'      => ['char(80)'],
84
          'title'     => ['varchar(80)'],
85
          'ingress'   => ['text'],
86
          'text'      => ['text'],
87
          'filters'   => ['char(80)'],
88
          'author'    => ['integer', 'not null'],
89
          'published' => ['datetime'],
90
          'created'   => ['datetime'],
91
          'updated'   => ['datetime'],
92
          'deleted'   => ['datetime']
93
        ]
94
      )->execute();
95
      
96
      $this->db->insert(
97
        'content',
98
        ['slug', 'url', 'type', 'title', 'ingress', 'text', 'filters', 'author', 'published', 'created']
99
      );
100
101
      $now = date('Y-m-d H:i:s');
102
103
      $this->db->execute([
104
        'welcome_to_your_new_blog',
105
        NULL,
106
        'blog-post',
107
        'Welcome to your new blog',
108
        'This is example-blogg to show your new blog system!',
109
        'You can start blog by visit [url=' . $this->url->create("{$this->urlPrefix}content/add/") . ']Add content[/url]',
110
        'bbcode',
111
        3,
112
        $now,
113
        $now
114
      ]);
115
      
116
      $this->db->execute([
117
        'welcome_to_your_new_page',
118
        'example-page',
119
        'page',
120
        'Welcome to your new page',
121
        'This is example-page to show your new page system!',
122
        'You can start makeing pages by visit [url=' . $this->url->create("{$this->urlPrefix}content/add/") . ']Add content[/url]',
123
        'bbcode',
124
        3,
125
        $now,
126
        $now
127
      ]);
128
      
129
      $this->db->dropTableIfExists('content_tags')->execute();
130
      
131
      $this->db->createTable(
132
        'content_tags',
133
        [
134
          'idContent' => ['integer', 'not null'],
135
          'tag'       => ['varchar(150)', 'not null'],
136
          'slug'      => ['varchar(150)', 'not null']
137
        ]
138
      )->execute();
139
      
140
      $this->db->insert(
141
        'content_tags',
142
        ['idContent', 'tag', 'slug']
143
      );
144
      
145
      $this->db->execute([
146
        1,
147
        'New blog',
148
        'new_blog'
149
      ]);
150
151
      $this->db->execute([
152
        1,
153
        'Blog information',
154
        'blog_information'
155
      ]);
156
      
157
      $this->views->add('text-content/action-finish', [
158
          'title'   => $title,
159
          'msg'     => "Content and content tags database tables " . strtolower($toDo). " was successful!"
160
      ], 'main');
161
      
162
    }
163
    else{      
164
      $this->views->add('text-content/action', [
165
          'title'   => $title,
166
          'toDo'    => strtolower($toDo),
167
          'toWhat'  => $toWhat,
168
          'form'    => $form->getHTML(['novalidate' => true])
169
      ], 'main');
170
    }
171
    
172
    $this->theme->setTitle($title);
173
  }
174
  
175
  /**
176
	 *  List content (by type)
177
   *
178
	 * @param     string  $type	  Type to list
179
   * @param     int     $page   Page that paging is on
180
	 * @return		void
181
	 */
182
	public function listAction($type = null, $published = false, $page = null){
183
    $type      = ($this->valid->checkType($type)) ? $type : null;
184
    $title     = "All Content {$type} listed";
185
    $published = boolval($published);
186
187
    $form   = $this->listForm($type, $published);
188
    $form->check();
189
    
190
    if(!is_null($type))
191
      $contents = $this->content->getAllContentOfType($type, $page, $this->contentPerPage, $published);
192
    else
193
      $contents = $this->content->getAllContent($page, $this->contentPerPage, $published);
194
    
195
    $contents = $this->prepareListContent($contents);
196
    
197
    $this->theme->setTitle($title);
198
    $this->views->add('text-content/list', 
199
      [
200
        'title'     => $title,
201
        'form'      => $form->getHTML(array('novalidate' => true)),
202
        'contents' 	=> $contents,
203
        'addUrl'	  => $this->url->create("{$this->urlPrefix}content/add/"),
204
        'setupUrl'  => $this->url->create("{$this->urlPrefix}content/setup/")
205
      ]
206
    );
207
208
  }
209
  
210
  /**
211
   * Add content to database
212
   *
213
   * @return    void
214
   */
215
  public function addAction(){
216
    $action = "Add";
217
    $title = "{$action} content";
218
    
219
    $form = $this->contentForm();
220
    $form->check();
221
    
222
    $this->theme->setTitle($title);
223
    
224
    $this->views->add('text-content/post', [
225
        'title'  => $title,
226
        'action' => $action,
227
        'form'   => $form->getHTML(array('novalidate' => true))
228
    ]);
229
  }
230
  
231
  /**
232
   * Edit content in database
233
   *
234
   * @param     int   $id   Index for content to edit
235
   * @return    void
236
   */
237
  public function editAction($id = null){
238
    $action = "Edit";
239
    $title  = "{$action} content";
240
    $url    = $this->url->create("{$this->urlPrefix}content/");
241
    
242
    if(is_null($id) || !is_numeric($id))
243
      $this->response->redirect($url);
244
    
245
    $content = $this->content->getContentById($id, false);
246
    
247
    if(is_null($content->id))
248
      $this->response->redirect($url);
249
    
250
    $form = $this->contentForm($content);
251
    $form->check();
252
    
253
    $this->theme->setTitle($title);
254
    
255
    $this->views->add('text-content/post', [
256
        'title'  => $title,
257
        'action' => $action,
258
        'form'   => $form->getHTML(array('novalidate' => true))
259
    ]);
260
  }
261
	
262
	/**
263
	 * Remove content
264
	 *
265
   * @param   int     $id       Index to content to remove
266
	 * @return  string  $error    Database-error msg
267
	 */
268
	public function removeAction($id = null){
269
		$action = "Delete";
270
    $title = "Delete content";
271
    $url = $this->url->create("{$this->urlPrefix}content/");
272
    
273
    if(is_null($id) || !is_numeric($id))
274
			$this->response->redirect($url);
275
    
276
    $content = $this->content->find($id);
277
    
278
    if(is_null($content->id))
279
      $this->response->redirect($url);
280
    
281
    $form = $this->confirmForm($url);
282
    $status = $form->Check();
283
    
284
    if ($status === true) {
285
      $now = date('Y-m-d H:i:s');
286
      
287
      $content->deleted = $now;
288
      $content->save();
289
      
290
      $this->response->redirect($url);
291
    }
292
    
293
    $this->theme->setTitle($title);
294
    $this->views->add('text-content/action', [
295
      'title'  => $title,
296
      'toDo'    => strtolower($action),
297
      'toWhat'  => strtolower($this->valid->getTypeTitle($content->type)),
298
      'which'   => htmlspecialchars($content->title, ENT_QUOTES),
299
      'form'    => $form->getHTML(['novalidate' => true]),
300
    ], 'main');
301
	}
302
  
303
  /**
304
   * Prepare form to add or edit content
305
   *
306
   * @param   string                $type       Selected content-type
307
   * @param   boolean               $published  If content should be published already
308
   * @return  \Mos\HTMLForm\CForm   $form       CForm object
309
   */
310
  private function listForm($type = null, $published = false){
311
    
312
    $type_options      = array_merge([0 => "Select a type of content"], $this->valid->getTypes());
313
    
314
    $form = new \Mos\HTMLForm\CForm([], [
315
        'type' => [
316
          'type'        => 'select',
317
          'label'       => 'Type of content:',
318
          'options'     => $type_options,
319
          'value'       => (isset($type)) ? $type : ''
320
        ],
321
        'published' => [
322
          'type'        => 'checkbox',
323
          'label'       => 'Published',
324
          'checked'     => $published,
325
          'value'       => 1
326
        ],
327
        'submit' => [
328
          'value' 		=> 'Filter',
329
          'type'      => 'submit',
330
          'callback'  => function ($form) {
331
            $published = ($this->request->getPost('published')) ? 1 : 0;
332
            $type      = $form->Value('type');
333
            
334
            $this->response->redirect($this->url->create("{$this->urlPrefix}content/list/{$type}/{$published}"));
335
          }
336
        ]
337
    ]);
338
    
339
    return $form;
340
  }
341
  
342
  /**
343
   * Prepare form to add or edit content
344
   *
345
   * @param   object                $values     Content values to add form elements
346
   * @return  \Mos\HTMLForm\CForm   $form       CForm object
347
   */
348 1
  private function contentForm($values = null){
349
    if(isset($values) && is_object($values)){
350
      $valArr = get_object_vars($values);
351
      extract($valArr);
352
    }
353
    
354
    $slug = (isset($slug)) ? $slug : NULL;
355
    
356
    $type_options = $this->valid->getTypes();
357
    
358
    $form = new \Mos\HTMLForm\CForm([], [
359
        'id'      => [
360
          'type'        => 'hidden',
361
          'value'       => (isset($id)) ? $id : 0
362
        ],
363
        'title' => [
364
          'type'        => 'text',
365
          'label'       => 'Title: (Between ' . $this->miniLength . ' to 80 chars)',
366
          'maxlength'   => 80,
367
          'required'    => true,
368
          'value'       => (isset($title)) ? $title : '',
369
          'validation'  => [
370
                              'custom_test' => array(
371
                                'message' => 'Minmum length is ' . $this->miniLength . ' chars.', 
372
                                'test'    => array($this, 'minimumLength')
373
                              )
374
                           ]
375
        ],
376
        'url' => [
377
          'type'        => 'text',
378
          'label'       => 'Url:',
379
          'maxlength'   => 80,
380 1
          'value'       => (isset($url)) ? $url : '',
381
          'required'    => false, 
382
          'validation'  => [
383
                              'custom_test' => array(
384
                                'message' => 'Url is not in accepted-format for url:s (accepted characters is \'a-z0-9-_()\').', 
385
                                'test'    => array($this, 'validateSlug')
386
                              )
387
                           ]
388
        ],
389
        'ingress' => [
390
          'type'        => 'textarea',
391
          'label'       => 'Ingress: (minimum 3 chars)',
392
          'value'       => (isset($ingress)) ? $ingress : '',
393
          'required'    => true,
394
          'validation'  => [
395
                              'custom_test' => array(
396
                                'message' => 'Minmum length is ' . $this->miniLength . ' chars.', 
397
                                'test'    => array($this, 'minimumLength')
398
                              )
399
                           ]
400
        ],
401
        'text' => [
402
          'type'        => 'textarea',
403
        	'label'       => 'Text: (minimum ' . $this->miniLength . ' chars)',
404
          'value'       => (isset($text)) ? $text : '',
405
          'required'    => true,
406
          'validation'  => [
407
                            'custom_test' => array(
408
                              'message' => 'Minmum length is ' . $this->miniLength . ' chars.', 
409
                              'test'    => array($this, 'minimumLength')
410
                            )
411
                           ]
412
        ],
413
        'type' => [
414
          'type'        => 'select',
415
          'label'       => 'Type of content:',
416
          'options'     => $type_options,
417
          'value'       => (isset($type)) ? $type : '',
418
          'required'    => true,
419
          'validation'  => [
420
                              'not_empty',
421
                              'custom_test' => array(
422
                                'message' => 'You need to select a existing type.', 
423
                                'test'    => array($this, 'checkType')
424
                              )
425
                           ]
426
        ],
427
        'tags' => [
428
          'type'        => 'text',
429
          'label'       => 'Tags: (Seperate by \',\')',
430
          'value'       => (isset($tags)) ? $tags : '',
431
          'required'    => false
432
        ],
433
        'filters' => [
434
          'type'        => 'checkbox-multiple',
435
          'label'       => 'Text filter:',
436
          'values'      => $this->valid->getFilters(),
437
          'checked'     => (isset($filters)) ? explode(',', $filters) : array(),
438
          'validation'  => [
439
                              'custom_test' => array(
440
                                'message' => 'You need to select a existing type.', 
441
                                'test'    => array($this, 'checkFilter')
442
                              )
443
                           ]
444
        ],
445
        'published' => [
446
          'type'        => 'datetime',
447
          'label'       => 'Published: (YYYY-MM-DD HH:MM:SS)',
448
          'value'       => (isset($published)) ? $published : '',
449
          'validation'  => [
450
                              'custom_test' => array(
451
                                'message' => 'It need to be in a correct date and time with format: YYYY-MM-DD HH:MM:SS.', 
452
                                'test'    => array($this, 'checkDatetime')
453
                              )
454
                           ]
455
        ],
456
        'publishedNow' => [
457
          'type'        => 'checkbox',
458
          'label'       => 'Publish now:',
459
          'checked'     => (!isset($published) && !isset($id)),
460
          'value'       => 'yes'
461
        ],
462
        'submit' => [
463
          'value' 		=> 'Save',
464
          'type'      => 'submit',
465
          'callback'  => function ($form) use($slug) {
466
            return $this->saveContent($form, $slug);
467
          }
468
        ]
469
    ]);
470
    
471
    return $form;
472
  }
473
  
474
  /**
475
   * Prepare confirmation form
476
   *
477
   * @param   string                $returnUrl       Return url
478
   * @return  \Mos\HTMLForm\CForm   $form            Form-object
479
   */
480
  public function confirmForm($returnUrl = null){
481
    $returnUrl = (isset($returnUrl)) ? $returnUrl : $this->request->getBaseUrl();
482
    
483
    $form = new \Mos\HTMLForm\CForm([], [
484
        'submit' => [
485
          'type'     => 'submit',
486
          'value'    => 'Yes',
487
          'callback' => function() {
488
            return true;
489
          }
490
        ],
491
        'submit-no' => [
492
          'type'     => "submit",
493
          'value'    => 'No',
494
          'callback' => function() use($returnUrl) {
495
            $this->response->redirect($returnUrl);
496
          }
497
        ]
498
      ]
499
    );
500
		
501
    // Check the status of the form
502
    return $form;
503
  }
504
  
505
  /**
506
   * Save content to database
507
   *
508
   * @param   \Mos\HTMLForm\CForm   $form       Form object
509
   * @param   string                $oldSlug    Old slug for content to compare
510
   * @return  boolean               false/true  If saving fail, return false
511
   */
512
  private function saveContent($form, $oldSlug = null){
513
    // Prepare content for saving
514
    $content = $this->prepareSaveContent($form, $oldSlug);
515
    
516
    // Save content
517
    $content = $this->content->save($content);
518
    
519
    // Saving fail
520
    if(!$this->content->id)
521
      return false;
522
    // Save tags for content to database
523
    else if($content['id'] != 0)
524
      $this->saveTags($form->Value('tags'), $this->content->id);
525
    
526
    $this->response->redirect($this->url->create("{$this->urlPrefix}content/"));
527
    return true;
528
  }
529
530
  /**
531
   * Save tags for content to database
532
   *
533
   * @param   string   $tags     Tags for content
534
   * @param   int      $id       Content index
535
   */
536
  private function saveTags($tags, $id){
537
    $this->db->delete(
538
      'content_tags',
539
      'idContent = ?'
540
    )->execute([$id]);
541
    
542
    $this->db->insert(
543
      'content_tags',
544
      ['idContent', 'tag', 'slug']
545
    );
546
    
547
    if(isset($tags) && !is_null($tags)){
548
      $tagsArr = explode(",", $tags);
549
      
550
      foreach($tagsArr as $tag){
551
        $tag = trim($tag);
552
        $this->db->execute([
553
          $id,
554
          $tag,
555
          $this->valid->slugify($tag)
556
        ]);
557
      }
558
    }
559
  }
560
  
561
  /**
562
   * Prepare contents for show in list view
563
   *
564
   * @param   object  $contents   Object with content objects
565
   * @return  array   $results    Array with prepare content objects
566
   */
567 1
  public function prepareListContent($contents){
568 1
    $results = array();
569
    
570 1
    foreach($contents AS $key => $content){
571 1
      $available = $this->valid->checkIfAvailable($content->published);
572 1
      $results[$key] = (object)[];
573
      
574 1
      foreach($content as $key2 => $value){
575 1
        $results[$key]->{$key2} = $value;
576 1
      }
577
      
578 1
      $results[$key]->typeTxt      = $this->valid->getTypeTitle($content->type);
579 1
      $results[$key]->title        = htmlspecialchars($content->title, ENT_QUOTES);
580 1
      $results[$key]->editUrl      = $this->url->create("{$this->urlPrefix}content/edit/{$content->id}");
581 1
      $results[$key]->removeUrl    = $this->url->create("{$this->urlPrefix}content/remove/{$content->id}");
582 1
      $results[$key]->showUrl      = $this->valid->getUrlToContent($content);
583 1
      $results[$key]->available    = ((!$available) ? "not-" : null) . "published";
584 1
      $results[$key]->publishedTxt  = ($available) ? $contents[$key]->published : "Not published yet";
585 1
    }
586
    
587 1
    return $results;
588
  }
589
  
590
  /**
591
   * Prepare save of content to database
592
   *
593
   * @param   object    $form     Form object
594
   * @param   string    $oldSlug  Old slug for content to compare
595
   * @return  array     $content  Prepare content array
596
   */  
597 1
  public function prepareSaveContent($form, $oldSlug = null){
598 1
    $now = date('Y-m-d H:i:s');
599
    
600
    // Prepare new slug
601 1
    $newSlug = $this->prepareNewSlug($form->Value('title'), $form->Value('type'), $oldSlug);
602
    
603
    $content = array(
604 1
      'title'     => $form->Value('title'),
605 1
      'slug'      => $newSlug,
606 1
      'url'       => $form->Value('url'),
607 1
      'ingress'   => $form->Value('ingress'),
608 1
      'text'      => $form->Value('text'),
609 1
      'type'      => $form->Value('type'),
610 1
      'filters'   => ($form->Value('filters')) ? implode(",", $form->Value('filters')) : '',
611 1
      'published' => ($form->Value('publishedNow') && $form->Value('publishedNow') == 'yes') ? $now : $form->Value('published')
612 1
    );
613
    
614 1
    $id = ($form->Value('id')) ? intval($form->Value('id')) : 0;
615
    
616 1
    if($id != 0){
617 1
      $content['updated'] = $now;
618 1
      $content['id']      = $id;
619 1
    }
620
    else{
621 1
      $content['created'] = $now;
622 1
      $content['author']  = 0;//$this->user->getUserId();
623
    }
624
    
625 1
    return $content;
626
  }
627
  
628
  /**
629
   * Prepare new slug for content by title
630
   *
631
   * @param   string    $title      Content title to make slug by
632
   * @param   string    $type       Content type
633
   * @param   string    $oldSlug    Old slug for content to compare
634
   * @return  string    $newSlug    New unique slug for content
635
   */
636 1
  public function prepareNewSlug($title, $type, $oldSlug = null){
637 1
    $newSlug = $this->valid->slugify($title);
638
    
639 1
    if($oldSlug != $newSlug && isset($newSlug))
640 1
      $newSlug = $this->content->makeSlugToContent($newSlug, $type);
641
    
642 1
    return $newSlug;
643
  }
644
  
645
  /**
646
   * Validate minimum length
647
   *
648
   * @param   string    $text       Text to validate
649
   * @return  boolean   True/False  Validate status
650
   */
651 1
  public function minimumLength($text = null){
652 1
    return $this->valid->minimumLength($text);
653
  }
654
  
655
  /**
656
   * Validate slug
657
   *
658
   * @param   string    $slug       Slug to validate
659
   * @return  boolean   True/False  Validate status
660
   */
661 1
  public function validateSlug($slug = null){
662 1
    return $this->valid->validateSlug($slug);
663
  }
664
  
665
  /**
666
   * Validate type
667
   *
668
   * @param   string    $type   Type to validate
669
   * @return  boolean   True/False  Validate status
670
   */
671 1
  public function checkType($type = null){
672 1
    return $this->valid->checkType($type);
673
  }
674
  
675
  /**
676
   * Validate filter
677
   *
678
   * @param   string    $filter   Filter to validate
679
   * @return  boolean   True/False  Validate status
680
   */
681 1
  public function checkFilter($filter = null){
682 1
    return $this->valid->checkFilter($filter);
683
  }
684
  
685
  /**
686
   * Validate date time
687
   *
688
   * @param   string    $datetime   Date time to validate
689
   * @return  boolean   True/False  Validate status
690
   */
691 1
  public function checkDatetime($datetime = null){
692 1
    return $this->valid->checkDatetime($datetime);
693
  }
694
}