Completed
Push — develop ( 92de50...a0aee2 )
by Schlaefer
06:57
created

PostingsController::edit()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 5
nop 0
dl 0
loc 31
rs 9.1128
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\Entity\Entry;
17
use App\Model\Table\EntriesTable;
18
use Cake\Core\Configure;
19
use Cake\Http\Exception\BadRequestException;
20
use Cake\Http\Exception\NotFoundException;
21
use Saito\Exception\SaitoForbiddenException;
22
use Saito\Posting\PostingInterface;
23
24
/**
25
 * Endpoint for adding/POST and editing/PUT posting
26
 *
27
 * @property EntriesTable $Entries
28
 */
29
class PostingsController extends ApiAppController
30
{
31
    /**
32
     * {@inheritDoc}
33
     */
34
    public function initialize()
35
    {
36
        parent::initialize();
37
        $this->loadModel('Entries');
38
    }
39
40
    /**
41
     * Add a a new posting
42
     *
43
     * @return void
44
     */
45
    public function add(): void
46
    {
47
        $data = $this->request->getData();
48
49
        /** @var Entry */
50
        $posting = $this->Entries->createPosting($data, $this->CurrentUser);
0 ignored issues
show
Bug introduced by
It seems like $data defined by $this->request->getData() on line 47 can also be of type null or string; however, App\Model\Table\EntriesTable::createPosting() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
51
52
        if (empty($posting)) {
53
            throw new BadRequestException();
54
        }
55
56
        $errors = $posting->getErrors();
57
58
        if (!count($errors)) {
59
            $this->set(compact('posting'));
60
61
            return;
62
        }
63
64
        $this->set(compact('errors'));
65
        $this->viewBuilder()->setTemplate('/Error/json/entityValidation');
66
    }
67
68
    /**
69
     * Edit an existing posting
70
     *
71
     * @return void
72
     */
73
    public function edit(): void
74
    {
75
        $data = $this->request->getData();
76
77
        if (empty($data['id'])) {
78
            throw new BadRequestException('No posting-id provided.');
79
        }
80
81
        $id = $data['id'];
82
        $posting = $this->Entries->get($id, ['return' => 'Entity']);
83
        if (!$posting) {
84
            throw new NotFoundException('Posting not found.');
85
        }
86
87
        $updatedPosting = $this->Entries->updatePosting($posting, $data, $this->CurrentUser);
0 ignored issues
show
Bug introduced by
It seems like $data defined by $this->request->getData() on line 75 can also be of type string; however, App\Model\Table\EntriesTable::updatePosting() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
88
89
        if (!$updatedPosting) {
90
            throw new BadRequestException('Posting could not be saved.');
91
        }
92
93
        if (!$updatedPosting->hasErrors()) {
94
            $this->set('posting', $updatedPosting);
95
            $this->render('/Postings/json/add');
96
97
            return;
98
        }
99
100
        $errors = $updatedPosting->getErrors();
101
        $this->set(compact('errors'));
102
        $this->viewBuilder()->setTemplate('/Error/json/entityValidation');
103
    }
104
105
    /**
106
     * Serves meta information required to add or edit a posting
107
     *
108
     * @return void
109
     */
110
    public function meta(): void
111
    {
112
        $id = $this->getRequest()->getQuery('id', null);
113
        $isEdit = !empty($id);
114
        $pid = $this->getRequest()->getQuery('pid', null);
115
        $isAnswer = !empty($pid);
116
117 View Code Duplication
        if ($isAnswer) {
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...
118
            /** @var PostingInterface */
119
            $parent = $this->Entries->get($pid);
0 ignored issues
show
Documentation introduced by
$pid is of type string|array, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
120
121
            // Don't leak content of forbidden categories
122
            if ($parent->isAnsweringForbidden()) {
123
                throw new SaitoForbiddenException(
124
                    'Access to parent in PostingsController:meta() forbidden.',
125
                    ['CurrentUser' => $this->CurrentUser]
126
                );
127
            }
128
129
            $this->set('parent', $parent);
130
        }
131
132 View Code Duplication
        if ($isEdit) {
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...
133
            /** @var PostingInterface */
134
            $posting = $this->Entries->get($id);
0 ignored issues
show
Documentation introduced by
$id is of type string|array, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
135
            if (!$posting->isEditingAllowed()) {
136
                throw new SaitoForbiddenException(
137
                    'Access to posting in PostingsController:meta() forbidden.',
138
                    ['CurrentUser' => $this->CurrentUser]
139
                );
140
            }
141
            $this->set('posting', $posting);
142
        }
143
144
        $settings = Configure::read('Saito.Settings');
145
146
        $this->set(compact('isAnswer', 'isEdit', 'settings'));
147
148
        $action = $isAnswer ? 'answer' : 'thread';
149
        $categories = $this->CurrentUser->getCategories()->getAll($action, 'list');
150
        $this->set('categories', $categories);
151
    }
152
}
153