ThreadActionsController::threadAction()   B
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 34
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 34
rs 8.439
c 0
b 0
f 0
cc 5
eloc 19
nc 4
nop 1
1
<?php
2
3
/*
4
 * This file is part of the MilioooMessageBundle package.
5
 *
6
 * (c) Michiel boeckaert <[email protected]>
7
 * This source file is subject to the MIT license that is bundled
8
 * with this source code in the file LICENSE.
9
 */
10
11
namespace Miliooo\MessagingBundle\Controller;
12
13
use Miliooo\Messaging\User\ParticipantInterface;
14
use Symfony\Component\HttpFoundation\Request;
15
use Miliooo\Messaging\Manager\ThreadStatusManagerInterface;
16
use Miliooo\Messaging\ThreadProvider\SecureThreadProviderInterface;
17
use Miliooo\Messaging\User\ParticipantProviderInterface;
18
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
19
use Miliooo\Messaging\Model\ThreadInterface;
20
use Miliooo\Messaging\ValueObjects\ThreadStatus;
21
use Miliooo\Messaging\Model\ThreadMetaInterface;
22
use Symfony\Component\HttpFoundation\RedirectResponse;
23
use Miliooo\Messaging\Helpers\FlashMessages\FlashMessageProviderInterface;
24
use Symfony\Component\Routing\RouterInterface;
25
26
/**
27
 * This class is responsible for handling thread actions.
28
 *
29
 * @author Michiel Boeckaert <[email protected]>
30
 */
31
class ThreadActionsController
32
{
33
    /**
34
     * A thread status manager interface.
35
     *
36
     * @var ThreadStatusManagerInterface
37
     */
38
    private $threadStatusManager;
39
40
    /**
41
     * A secure thread provider.
42
     *
43
     * @var SecureThreadProviderInterface
44
     */
45
    private $threadProvider;
46
47
    /**
48
     * A participant provider instance.
49
     *
50
     * @var ParticipantProviderInterface
51
     */
52
    private $participantProvider;
53
54
    /**
55
     * A flash message provider instance.
56
     *
57
     * @var FlashMessageProviderInterface
58
     */
59
    private $flashMessageProvider;
60
61
    /**
62
     * A router instance.
63
     *
64
     * @var RouterInterface
65
     */
66
    private $router;
67
    /**
68
     * @param ThreadStatusManagerInterface  $threadStatusManager
69
     * @param SecureThreadProviderInterface $threadProvider
70
     * @param ParticipantProviderInterface  $participantProvider
71
     * @param FlashMessageProviderInterface $flashMessageProvider
72
     * @param RouterInterface               $router
73
     */
74
    public function __construct(
75
        ThreadStatusManagerInterface $threadStatusManager,
76
        SecureThreadProviderInterface $threadProvider,
77
        ParticipantProviderInterface $participantProvider,
78
        FlashMessageProviderInterface $flashMessageProvider,
79
        RouterInterface $router
80
    ) {
81
        $this->threadStatusManager = $threadStatusManager;
82
        $this->threadProvider = $threadProvider;
83
        $this->participantProvider = $participantProvider;
84
        $this->flashMessageProvider = $flashMessageProvider;
85
        $this->router = $router;
86
    }
87
88
    /**
89
     * @param Request $request
90
     *
91
     * @return RedirectResponse
92
     */
93
    public function threadAction(Request $request)
94
    {
95
        $threadIds = $this->getThreadIdsFromRequest($request);
96
        $threadAction = $this->getThreadActionFromRequest($request);
97
        $loggedInUser = $this->participantProvider->getAuthenticatedParticipant();
98
99
        //no action needed here... probably no threads selected but pressed submit
100
        if (empty($threadIds) || !$threadAction) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $threadAction of type false|string is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
101
            //the user has not selected any threads
102
            if (empty($threadIds)) {
103
                //add flash messsage that they have no threads selected
104
                $this->flashMessageProvider->addFlash(FlashMessageProviderInterface::TYPE_ERROR, 'flash.thread_updates.no_threads_selected');
105
            } else {
106
                //there is an error with the threadAction but this should not happen unless we screw up
107
                $this->flashMessageProvider->addFlash(FlashMessageProviderInterface::TYPE_ERROR, 'flash.thread_updates_error');
108
            }
109
            //redirect them to the referer
110
            return $this->redirectToReferrer($request);
111
        }
112
113
       switch($threadAction)
0 ignored issues
show
Coding Style introduced by
Expected 1 space after SWITCH keyword; 0 found
Loading history...
114
       {
115
           case "archive_thread":
116
               $this->archiveThreads($threadIds, $loggedInUser);
117
               break;
118
119
           default:
120
               $this->flashMessageProvider->addFlash(FlashMessageProviderInterface::TYPE_ERROR, 'flash.thread_updates.unknown_action');
121
               return $this->redirectToReferrer($request);
122
               break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
123
       }
124
125
        return $this->redirectResponse($request);
126
    }
127
128
    /**
129
     * Gets the thread ids from the request.
130
     *
131
     * @param Request $request
132
     *
133
     * @return array|false An array with thread ids selected or false when no thread id array given.
134
     */
135
136
    protected function getThreadIdsFromRequest(Request $request)
137
    {
138
        return $request->request->get('selected_threads', []);
139
    }
140
141
    /**
142
     * Archive threads.
143
     *
144
     * @param array                $threadIds
145
     * @param ParticipantInterface $loggedInUser
146
     */
147
    protected function archiveThreads($threadIds, ParticipantInterface $loggedInUser)
148
    {
149
        //do the thread update if there are any threads to update
150
        $processed = $this->doArchiveThreads($threadIds, $loggedInUser);
151
        $this->addFlashMessage($processed);
152
    }
153
154
    /**
155
     * Gets the thread action from the request.
156
     *
157
     * @param Request $request
158
     *
159
     * @return string|false
160
     */
161
    protected function getThreadActionFromRequest(Request $request)
162
    {
163
        $threadAction = $request->request->get('thread_action');
164
        if (empty($threadAction) || !is_string($threadAction)) {
165
            return false;
166
        }
167
168
        return $threadAction;
169
    }
170
171
    /**
172
     * Gets the threads from the thread ids for whom the user has access to view.
173
     *
174
     * @param array                $threadIds
175
     * @param ParticipantInterface $loggedInUser
176
     *
177
     * @return ThreadInterface[] An array with threadInterfaces for whom the user has permission to view them.
178
     */
179
    protected function getAllowedThreads($threadIds, ParticipantInterface $loggedInUser)
180
    {
181
        $threadArray = [];
182
        foreach ($threadIds as $threadId) {
183
            //try to get the thread, it returns null when not found or throws an exception...
184
            try {
185
                $thread = $this->threadProvider->findThreadForParticipant($loggedInUser, $threadId);
186
            } catch (AccessDeniedException $e) {
187
                $thread = null;
188
            }
189
190
            //we only want an array with valid thread objects...
191
            if (is_object($thread) && $thread instanceof ThreadInterface) {
192
                $threadArray[] = $thread;
193
            }
194
        }
195
196
        return $threadArray;
197
    }
198
199
    /**
200
     * Does the archiving of the threads by calling the thread status manager.
201
     *
202
     * @param array                $threadIds
203
     * @param ParticipantInterface $loggedInUser
204
     *
205
     * @return boolean true if there are threads processed, false otherwise
206
     */
207
    protected function doArchiveThreads($threadIds, ParticipantInterface $loggedInUser)
0 ignored issues
show
Coding Style introduced by
function doArchiveThreads() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
208
    {
209
        $threads = $this->getAllowedThreads($threadIds, $loggedInUser);
210
        if ($threads) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $threads of type Miliooo\Messaging\Model\ThreadInterface[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
211
            //make a thread status value object
212
            $threadStatus = new ThreadStatus(ThreadMetaInterface::STATUS_ARCHIVED);
213
            foreach ($threads as $thread) {
214
                $this->threadStatusManager->updateThreadStatusForParticipant($threadStatus, $thread, $loggedInUser);
215
            }
216
217
            return true;
218
        }
219
220
        return false;
221
    }
222
223
    /**
224
     * @param boolean $processed Whether or not there where thread status updates
225
     */
226
    protected function addFlashMessage($processed)
227
    {
228
        if ($processed) {
229
            $this->flashMessageProvider->addFlash(
230
                FlashMessageProviderInterface::TYPE_SUCCESS,
231
                'flash.thread_updates.archived_success'
232
            );
233
        } else {
234
        $this->flashMessageProvider->addFlash(
235
            FlashMessageProviderInterface::TYPE_ERROR,
236
            'flash.thread_updates.archived_no_threads'
237
        );
238
        }
239
    }
240
241
    /**
242
     * Redirects the user
243
     * @param Request $request
244
     *
245
     * @return RedirectResponse
246
     */
247
    private function redirectResponse(Request $request)
248
    {
249
        $currentFolder = $request->request->get('folder', 'inbox');
250
        $url = $this->router->generate('miliooo_message_'.$currentFolder);
251
252
        return new RedirectResponse($url);
253
    }
254
255
    /**
256
     * @param Request $request
257
     * @return RedirectResponse
258
     */
259
    protected function redirectToReferrer(Request $request)
260
    {
261
        //redirect them to the referrer if it's set
262
        $referrer = $request->server->get('HTTP_REFERER');
263
        if ($referrer) {
264
            return new redirectResponse($referrer);
265
        } else {
266
            return $this->redirectResponse($request);
267
        }
268
    }
269
}
270