Completed
Branch #338-Save_posting_before_movin... (60770e)
by Schlaefer
02:30
created

PreviewController::preview()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 45

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 8
nop 0
dl 0
loc 45
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * Saito - The Threaded Web Forum
7
 *
8
 * @copyright Copyright (c) the Saito Project Developers
9
 * @link https://github.com/Schlaefer/Saito
10
 * @license http://opensource.org/licenses/MIT
11
 */
12
13
namespace App\Controller;
14
15
use Api\Controller\ApiAppController;
16
use App\Model\Table\EntriesTable;
17
use Cake\I18n\Time;
18
use Cake\View\Helper\IdGeneratorTrait;
19
use Saito\App\Registry;
20
21
/**
22
 * Class EntriesController
23
 *
24
 * @property EntriesTable $Entries
25
 */
26
class PreviewController extends ApiAppController
27
{
28
    use IdGeneratorTrait;
29
30
    /**
31
     * Generate posting preview for JSON frontend.
32
     *
33
     * @return \Cake\Network\Response|void
34
     */
35
    public function preview()
36
    {
37
        $this->loadModel('Entries');
38
39
        $data = [
40
            'category_id' => $this->request->getData('category_id'),
41
            'edited_by' => null,
42
            'fixed' => false,
43
            'id' => 'preview',
44
            'ip' => '',
45
            'last_answer' => bDate(),
46
            'name' => $this->CurrentUser->get('username'),
47
            'pid' => $this->request->getData('pid') ?: 0,
48
            'solves' => 0,
49
            'subject' => $this->request->getData('subject'),
50
            'text' => $this->request->getData('text'),
51
            'user_id' => $this->CurrentUser->getId(),
52
            'time' => new Time(),
53
            'views' => 0,
54
        ];
55
56
        if (!empty($data['pid'])) {
57
            $parent = $this->Entries->get($data['pid']);
58
            $data = $this->Entries->prepareChildPosting($parent, $data);
59
        }
60
61
        $newEntry = $this->Entries->newEntity($data);
62
        $errors = $newEntry->getErrors();
63
64
        if (empty($errors)) {
65
            // no validation errors
66
            $newEntry['user'] = $this->CurrentUser->getSettings();
67
            $newEntry['category'] = $this->Entries->Categories->find()
68
                ->where(['id' => $newEntry['category_id']])
69
                ->first();
70
            $posting = Registry::newInstance(
71
                '\Saito\Posting\Posting',
72
                ['rawData' => $newEntry->toArray()]
73
            );
74
            $this->set(compact('posting'));
75
        } else {
76
            $this->set(compact('errors'));
77
            $this->viewBuilder()->setTemplate('/Error/json/entityValidation');
78
        }
79
    }
80
}
81