Completed
Push — master ( 28dda4...aabe55 )
by Craig
06:13
created

HookController   C

Complexity

Total Complexity 55

Size/Duplication

Total Lines 399
Duplicated Lines 7.52 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 30
loc 399
rs 6.8
c 0
b 0
f 0
wmc 55
lcom 1
cbo 2

6 Methods

Rating   Name   Duplication   Size   Complexity  
D editAction() 24 207 28
C toggleSubscribeAreaStatusAction() 3 62 11
C changeProviderAreaOrderAction() 3 35 7
A checkAjaxToken() 0 13 4
A isCapable() 0 7 3
A getExtensionsCapableOf() 0 11 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like HookController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use HookController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/*
4
 * This file is part of the Zikula package.
5
 *
6
 * Copyright Zikula Foundation - http://zikula.org/
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Zikula\Bundle\HookBundle\Controller;
13
14
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
15
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
16
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
17
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
20
use Zikula\Bundle\CoreBundle\Bundle\MetaData;
21
use Zikula\Bundle\HookBundle\Collector\HookCollectorInterface;
22
use Zikula\Core\Response\Ajax\AjaxResponse;
23
use Zikula\ExtensionsModule\Util as ExtensionsUtil;
24
use Zikula\ExtensionsModule\Entity\ExtensionEntity;
25
use Zikula\ThemeModule\Engine\Annotation\Theme;
26
27
/**
28
 * Class HookController
29
 * @Route("/hooks")
30
 */
31
class HookController extends Controller
32
{
33
    /**
34
     * @Route("/{moduleName}", options={"zkNoBundlePrefix" = 1})
35
     * @Method("GET")
36
     * @Theme("admin")
37
     * @Template
38
     *
39
     * Display hooks user interface
40
     *
41
     * @param string $moduleName
42
     * @return array
43
     * @throws AccessDeniedException Thrown if the user doesn't have admin permissions over the module
44
     */
45
    public function editAction($moduleName)
46
    {
47
        $templateParameters = [];
48
        // get module's name and assign it to template
49
        $templateParameters['currentmodule'] = $moduleName;
50
51
        // check if user has admin permission on this module
52
        if (!$this->get('zikula_permissions_module.api.permission')->hasPermission($moduleName . '::', '::', ACCESS_ADMIN)) {
53
            throw new AccessDeniedException();
54
        }
55
56
        $metaData = $this->get('kernel')->getModule($moduleName)->getMetaData();
57
        $moduleVersionObj = $this->get('zikula_hook_bundle.api.hook')->getHookContainerInstance($metaData);
0 ignored issues
show
Unused Code introduced by
$moduleVersionObj 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...
58
59
        // find out the capabilities of the module
60
        $isProvider = $this->isCapable($moduleName, HookCollectorInterface::HOOK_PROVIDER);
61
        $templateParameters['isProvider'] = $isProvider;
62
63
        $isSubscriber = $this->isCapable($moduleName, HookCollectorInterface::HOOK_SUBSCRIBER);
64
        $templateParameters['isSubscriber'] = $isSubscriber;
65
66
        $isSubscriberSelfCapable = $this->isCapable($moduleName, HookCollectorInterface::HOOK_SUBSCRIBE_OWN);
67
        $templateParameters['isSubscriberSelfCapable'] = $isSubscriberSelfCapable;
68
        $templateParameters['providerAreas'] = [];
69
70
        $nonPersistedProviders = $this->get('zikula_hook_bundle.collector.hook_collector')->getProviders();
71
        $nonPersistedSubscribers = $this->get('zikula_hook_bundle.collector.hook_collector')->getSubscribers();
72
73
        // get areas of module and bundle titles also
74
        if ($isProvider) {
75
            $providerAreas = $this->get('hook_dispatcher')->getProviderAreasByOwner($moduleName);
76
            $templateParameters['providerAreas'] = $providerAreas;
77
78
            $providerAreasToTitles = [];
79
            foreach ($providerAreas as $providerArea) {
80
                if (isset($nonPersistedProviders[$providerArea])) {
81
                    $providerAreasToTitles[$providerArea] = $nonPersistedProviders[$providerArea]->getTitle();
82
                }
83
            }
84
            $templateParameters['providerAreasToTitles'] = $providerAreasToTitles;
85
        }
86
        $templateParameters['subscriberAreas'] = [];
87
        $templateParameters['hooksubscribers'] = [];
88
89
        if ($isSubscriber) {
90
            $subscriberAreas = $this->get('hook_dispatcher')->getSubscriberAreasByOwner($moduleName);
91
            $templateParameters['subscriberAreas'] = $subscriberAreas;
92
93
            $subscriberAreasToTitles = [];
94
            $subscriberAreasToCategories = [];
95
            $subscriberAreasAndCategories = [];
96 View Code Duplication
            foreach ($subscriberAreas as $subscriberArea) {
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...
97
                if (isset($nonPersistedSubscribers[$subscriberArea])) {
98
                    $subscriberAreasToTitles[$subscriberArea] = $nonPersistedSubscribers[$subscriberArea]->getTitle();
99
                    $category = $nonPersistedSubscribers[$subscriberArea]->getCategory();
100
                }
101
                $subscriberAreasToCategories[$subscriberArea] = $category;
0 ignored issues
show
Bug introduced by
The variable $category does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
102
                $subscriberAreasAndCategories[$category][] = $subscriberArea;
103
            }
104
            $templateParameters['subscriberAreasToTitles'] = $subscriberAreasToTitles;
105
            $templateParameters['subscriberAreasToCategories'] = $subscriberAreasToCategories;
106
            $templateParameters['subscriberAreasAndCategories'] = $subscriberAreasAndCategories;
107
        }
108
109
        // get available subscribers that can attach to provider
110
        if ($isProvider && !empty($providerAreas)) {
111
            /** @var ExtensionEntity[] $hooksubscribers */
112
            $hooksubscribers = $this->getExtensionsCapableOf(HookCollectorInterface::HOOK_SUBSCRIBER);
113
            $amountOfHookSubscribers = count($hooksubscribers);
114
            $amountOfAvailableSubscriberAreas = 0;
115
            for ($i = 0; $i < $amountOfHookSubscribers; $i++) {
116
                $hooksubscribers[$i] = $hooksubscribers[$i]->toArray();
117
                // don't allow subscriber and provider to be the same
118
                // unless subscriber has the ability to connect to it's own providers
119
                if ($hooksubscribers[$i]['name'] == $moduleName) {
120
                    unset($hooksubscribers[$i]);
121
                    continue;
122
                }
123
                // does the user have admin permissions on the subscriber module?
124 View Code Duplication
                if (!$this->get('zikula_permissions_module.api.permission')->hasPermission($hooksubscribers[$i]['name'] . "::", '::', ACCESS_ADMIN)) {
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...
125
                    unset($hooksubscribers[$i]);
126
                    continue;
127
                }
128
129
                $metaData = $this->get('kernel')->getModule($hooksubscribers[$i]['name'])->getMetaData();
130
                $hooksubscriberVersionObj = $this->get('zikula_hook_bundle.api.hook')->getHookContainerInstance($metaData);
0 ignored issues
show
Unused Code introduced by
$hooksubscriberVersionObj 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...
131
132
                // get the areas of the subscriber
133
                $hooksubscriberAreas = $this->get('hook_dispatcher')->getSubscriberAreasByOwner($hooksubscribers[$i]['name']);
134
                $hooksubscribers[$i]['areas'] = $hooksubscriberAreas;
135
                $amountOfAvailableSubscriberAreas += count($hooksubscriberAreas);
136
137
                $hooksubscriberAreasToTitles = []; // and get the titles
138
                $hooksubscriberAreasToCategories = []; // and get the categories
139
                foreach ($hooksubscriberAreas as $hooksubscriberArea) {
140
                    if (isset($nonPersistedSubscribers[$hooksubscriberArea])) {
141
                        $hooksubscriberAreasToTitles[$hooksubscriberArea] = $nonPersistedSubscribers[$hooksubscriberArea]->getTitle();
142
                        $category = $nonPersistedSubscribers[$hooksubscriberArea]->getCategory();
143
                    }
144
                    $hooksubscriberAreasToCategories[$hooksubscriberArea] = $category;
145
                }
146
                $hooksubscribers[$i]['areasToTitles'] = $hooksubscriberAreasToTitles;
147
                $hooksubscribers[$i]['areasToCategories'] = $hooksubscriberAreasToCategories;
148
            }
149
            $templateParameters['hooksubscribers'] = $hooksubscribers;
150
            $templateParameters['total_available_subscriber_areas'] = $amountOfAvailableSubscriberAreas;
151
        } else {
152
            $templateParameters['total_available_subscriber_areas'] = 0;
153
        }
154
155
        // get providers that are already attached to the subscriber
156
        // and providers that can attach to the subscriber
157
        if ($isSubscriber && !empty($subscriberAreas)) {
158
            // get current sorting
159
            $currentSortingTitles = [];
160
            $currentSorting = [];
161
            $amountOfAttachedProviderAreas = 0;
162
            $amountOfSubscriberAreas = count($subscriberAreas);
163
            for ($i = 0; $i < $amountOfSubscriberAreas; $i++) {
164
                $sortsByArea = $this->get('hook_dispatcher')->getBindingsFor($subscriberAreas[$i]);
165
                foreach ($sortsByArea as $sba) {
166
                    $areaname = $sba['areaname'];
167
                    $category = $sba['category'];
168
169
                    if (!isset($currentSorting[$category])) {
170
                        $currentSorting[$category] = [];
171
                    }
172
173
                    if (!isset($currentSorting[$category][$subscriberAreas[$i]])) {
174
                        $currentSorting[$category][$subscriberAreas[$i]] = [];
175
                    }
176
177
                    array_push($currentSorting[$category][$subscriberAreas[$i]], $areaname);
178
                    $amountOfAttachedProviderAreas++;
179
180
                    // get hook provider from it's area
181
                    $sbaProviderModule = $this->get('hook_dispatcher')->getOwnerByArea($areaname);
182
183
                    $metaData = $this->get('kernel')->getModule($sbaProviderModule)->getMetaData();
184
                    $sbaProviderModuleVersionObj = $this->get('zikula_hook_bundle.api.hook')->getHookContainerInstance($metaData);
0 ignored issues
show
Unused Code introduced by
$sbaProviderModuleVersionObj 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...
185
186
                    // get the bundle title
187
                    if (isset($nonPersistedProviders[$areaname])) {
188
                        $currentSortingTitles[$areaname] = $nonPersistedProviders[$areaname]->getTitle();
189
                    }
190
                }
191
            }
192
            $templateParameters['areasSorting'] = $currentSorting;
193
            $templateParameters['areasSortingTitles'] = $currentSortingTitles;
194
            $templateParameters['total_attached_provider_areas'] = $amountOfAttachedProviderAreas;
195
196
            // get available providers
197
            /** @var ExtensionEntity[] $hookproviders */
198
            $hookproviders = $this->getExtensionsCapableOf(HookCollectorInterface::HOOK_PROVIDER);
199
            $amountOfHookProviders = count($hookproviders);
200
            $amountOfAvailableProviderAreas = 0;
201
            for ($i = 0; $i < $amountOfHookProviders; $i++) {
202
                $hookproviders[$i] = $hookproviders[$i]->toArray();
203
                // don't allow subscriber and provider to be the same
204
                // unless subscriber has the ability to connect to it's own providers
205
                if ($hookproviders[$i]['name'] == $moduleName && !$isSubscriberSelfCapable) {
206
                    unset($hookproviders[$i]);
207
                    continue;
208
                }
209
210
                // does the user have admin permissions on the provider module?
211 View Code Duplication
                if (!$this->get('zikula_permissions_module.api.permission')->hasPermission($hookproviders[$i]['name']."::", '::', ACCESS_ADMIN)) {
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...
212
                    unset($hookproviders[$i]);
213
                    continue;
214
                }
215
216
                $metaData = $this->get('kernel')->getModule($hookproviders[$i]['name'])->getMetaData();
217
                $hookproviderVersionObj = $this->get('zikula_hook_bundle.api.hook')->getHookContainerInstance($metaData);
0 ignored issues
show
Unused Code introduced by
$hookproviderVersionObj 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...
218
219
                // get the areas of the provider
220
                $hookproviderAreas = $this->get('hook_dispatcher')->getProviderAreasByOwner($hookproviders[$i]['name']);
221
                $hookproviders[$i]['areas'] = $hookproviderAreas;
222
                $amountOfAvailableProviderAreas += count($hookproviderAreas);
223
224
                $hookproviderAreasToTitles = []; // and get the titles
225
                $hookproviderAreasToCategories = []; // and get the categories
226
                $hookproviderAreasAndCategories = []; // and build array with category => areas
227 View Code Duplication
                foreach ($hookproviderAreas as $hookproviderArea) {
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...
228
                    if (isset($nonPersistedProviders[$hookproviderArea])) {
229
                        $hookproviderAreasToTitles[$hookproviderArea] = $nonPersistedProviders[$hookproviderArea]->getTitle();
230
                        $category = $nonPersistedProviders[$hookproviderArea]->getCategory();
231
                    }
232
                    $hookproviderAreasToCategories[$hookproviderArea] = $category;
233
                    $hookproviderAreasAndCategories[$category][] = $hookproviderArea;
234
                }
235
                $hookproviders[$i]['areasToTitles'] = $hookproviderAreasToTitles;
236
                $hookproviders[$i]['areasToCategories'] = $hookproviderAreasToCategories;
237
                $hookproviders[$i]['areasAndCategories'] = $hookproviderAreasAndCategories;
238
            }
239
            $templateParameters['hookproviders'] = $hookproviders;
240
            $templateParameters['total_available_provider_areas'] = $amountOfAvailableProviderAreas;
241
        } else {
242
            $templateParameters['hookproviders'] = [];
243
        }
244
        $templateParameters['hookDispatcher'] = $this->get('hook_dispatcher');
245
        $request = $this->get('request_stack')->getCurrentRequest();
246
        $request->attributes->set('_zkModule', $moduleName);
247
        $request->attributes->set('_zkType', 'admin');
248
        $request->attributes->set('_zkFunc', 'Hooks');
249
250
        return $templateParameters;
251
    }
252
253
    /**
254
     * @Route("/togglestatus", options={"expose"=true})
255
     * @Method("POST")
256
     *
257
     * Attach/detach a subscriber area to a provider area
258
     *
259
     * @param Request $request
260
     *
261
     *  subscriberarea string area to be attached/detached
262
     *  providerarea   string area to attach/detach
263
     *
264
     * @return AjaxResponse
265
     *
266
     * @throws \InvalidArgumentException Thrown if either the subscriber, provider or subscriberArea parameters are empty
267
     * @throws \RuntimeException Thrown if either the subscriber or provider module isn't available
268
     * @throws AccessDeniedException Thrown if the user doesn't have admin access to either the subscriber or provider modules
269
     */
270
    public function toggleSubscribeAreaStatusAction(Request $request)
271
    {
272
        $this->checkAjaxToken();
273
274
        // get subscriberarea from POST
275
        $subscriberArea = $request->request->get('subscriberarea', '');
276
        if (empty($subscriberArea)) {
277
            throw new \InvalidArgumentException($this->get('translator.default')->__('No subscriber area passed.'));
278
        }
279
280
        // get subscriber module based on area and do some checks
281
        $subscriber = $this->get('hook_dispatcher')->getOwnerByArea($subscriberArea);
282
        if (empty($subscriber)) {
283
            throw new \InvalidArgumentException($this->get('translator.default')->__f('Module "%s" is not a valid subscriber.', ['%s' => $subscriber]));
284
        }
285 View Code Duplication
        if (!$this->get('kernel')->isBundle($subscriber)) {
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...
286
            throw new \RuntimeException($this->get('translator.default')->__f('Subscriber module "%s" is not available.', $subscriber));
287
        }
288
        if (!$this->get('zikula_permissions_module.api.permission')->hasPermission($subscriber.'::', '::', ACCESS_ADMIN)) {
289
            throw new AccessDeniedException();
290
        }
291
292
        // get providerarea from POST
293
        $providerArea = $request->request->get('providerarea', '');
294
        if (empty($providerArea)) {
295
            throw new \InvalidArgumentException($this->get('translator.default')->__('No provider area passed.'));
296
        }
297
298
        // get provider module based on area and do some checks
299
        $provider = $this->get('hook_dispatcher')->getOwnerByArea($providerArea);
300
        if (empty($provider)) {
301
            throw new \InvalidArgumentException($this->get('translator.default')->__f('Module "%s" is not a valid provider.', ['%s' => $provider]));
302
        }
303
        if (!$this->get('kernel')->isBundle($provider)) {
304
            throw new \RuntimeException($this->get('translator.default')->__f('Provider module "%s" is not available.', $provider));
305
        }
306
        if (!$this->get('zikula_permissions_module.api.permission')->hasPermission($provider.'::', '::', ACCESS_ADMIN)) {
307
            throw new AccessDeniedException();
308
        }
309
310
        // check if binding between areas exists
311
        $binding = $this->get('hook_dispatcher')->getBindingBetweenAreas($subscriberArea, $providerArea);
312
        if (!$binding) {
313
            $this->get('hook_dispatcher')->bindSubscriber($subscriberArea, $providerArea);
314
        } else {
315
            $this->get('hook_dispatcher')->unbindSubscriber($subscriberArea, $providerArea);
316
        }
317
        $this->get('zikula.cache_clearer')->clear('symfony.config');
318
319
        // ajax response
320
        $response = [
321
            'result' => true,
322
            'action' => $binding ? 'unbind' : 'bind',
323
            'subscriberarea' => $subscriberArea,
324
            'subscriberarea_id' => md5($subscriberArea),
325
            'providerarea' => $providerArea,
326
            'providerarea_id' => md5($providerArea),
327
            'isSubscriberSelfCapable' => $this->isCapable($subscriber, HookCollectorInterface::HOOK_SUBSCRIBE_OWN)
328
        ];
329
330
        return new AjaxResponse($response);
331
    }
332
333
    /**
334
     * @Route("/changeorder", options={"expose"=true})
335
     * @Method("POST")
336
     *
337
     * changeproviderareaorder
338
     * This function changes the order of the providers' areas that are attached to a subscriber
339
     *
340
     * @param Request $request
341
     *
342
     *  subscriber    string     name of the subscriber
343
     *  providerorder array      array of sorted provider ids
344
     *
345
     * @return AjaxResponse
346
     *
347
     * @throws \InvalidArgumentException Thrown if the subscriber or subscriberarea parameters aren't valid
348
     * @throws \RuntimeException Thrown if the subscriber module isn't available
349
     * @throws AccessDeniedException Thrown if the user doesn't have admin access to the subscriber module
350
     */
351
    public function changeProviderAreaOrderAction(Request $request)
352
    {
353
        $this->checkAjaxToken();
354
355
        // get subscriberarea from POST
356
        $subscriberarea = $request->request->get('subscriberarea', '');
357
        if (empty($subscriberarea)) {
358
            throw new \InvalidArgumentException($this->get('translator.default')->__('No subscriber area passed.'));
359
        }
360
361
        // get subscriber module based on area and do some checks
362
        $subscriber = $this->get('hook_dispatcher')->getOwnerByArea($subscriberarea);
363
        if (empty($subscriber)) {
364
            throw new \InvalidArgumentException($this->get('translator.default')->__f('Module "%s" is not a valid subscriber.', ['%s' => $subscriber]));
365
        }
366 View Code Duplication
        if (!$this->get('kernel')->isBundle($subscriber)) {
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...
367
            throw new \RuntimeException($this->get('translator.default')->__f('Subscriber module "%s" is not available.', $subscriber));
368
        }
369
        if (!$this->get('zikula_permissions_module.api.permission')->hasPermission($subscriber.'::', '::', ACCESS_ADMIN)) {
370
            throw new AccessDeniedException();
371
        }
372
373
        // get providers' areas from POST
374
        $providerarea = $request->request->get('providerarea', '');
375
        if (!(is_array($providerarea) && count($providerarea) > 0)) {
376
            throw new \InvalidArgumentException($this->get('translator.default')->__('Providers\' areas order is not an array.'));
377
        }
378
379
        // set sorting
380
        $this->get('hook_dispatcher')->setBindOrder($subscriberarea, $providerarea);
381
382
        $ol_id = $request->request->get('ol_id', '');
383
384
        return new AjaxResponse(['result' => true, 'ol_id' => $ol_id]);
385
    }
386
387
    /**
388
     * Check the CSRF token.
389
     * Checks will fall back to $token check if automatic checking fails
390
     *
391
     * @param string $token Token, default null
392
     * @throws AccessDeniedException If the CSFR token fails
393
     * @throws \Exception if request is not an XmlHttpRequest
394
     * @return void
395
     */
396
    private function checkAjaxToken($token = null)
397
    {
398
        $currentRequest = $this->get('request_stack')->getCurrentRequest();
399
        if (!$currentRequest->isXmlHttpRequest()) {
400
            throw new \Exception();
401
        }
402
        // @todo how to SET the $_SERVER['HTTP_X_ZIKULA_AJAX_TOKEN'] ?
403
        $headerToken = ($currentRequest->server->has('HTTP_X_ZIKULA_AJAX_TOKEN')) ? $currentRequest->server->get('HTTP_X_ZIKULA_AJAX_TOKEN') : null;
404
        if ($headerToken == $currentRequest->getSession()->getId()) {
405
            return;
406
        }
407
        $this->get('zikula_core.common.csrf_token_handler')->validate($token);
408
    }
409
410
    private function isCapable($moduleName, $type)
411
    {
412
        $nonPersisted = $this->get('zikula_hook_bundle.collector.hook_collector')->isCapable($moduleName, $type);
413
        $persisted =  $this->get('zikula_extensions_module.api.capability')->isCapable($moduleName, $type) ? true : false;
414
415
        return $nonPersisted || $persisted;
416
    }
417
418
    private function getExtensionsCapableOf($type)
419
    {
420
        $nonPersistedOwners = $this->get('zikula_hook_bundle.collector.hook_collector')->getOwnersCapableOf($type);
421
        $nonPersisted = [];
422
        foreach ($nonPersistedOwners as $nonPersistedOwner) {
423
            $nonPersisted[] = $this->get('zikula_extensions_module.extension_repository')->findOneBy(['name' => $nonPersistedOwner]);
424
        }
425
        $persisted = $this->get('zikula_extensions_module.api.capability')->getExtensionsCapableOf($type);
426
427
        return array_merge($nonPersisted, $persisted);
428
    }
429
}
430