Completed
Push — master ( 4b2870...b9812c )
by Cheren
02:31
created

ProcessComponent::getRequestVars()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 2
1
<?php
2
/**
3
 * CakeCMS Core
4
 *
5
 * This file is part of the of the simple cms based on CakePHP 3.
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 *
9
 * @package   Core
10
 * @license   MIT
11
 * @copyright MIT License http://www.opensource.org/licenses/mit-license.php
12
 * @link      https://github.com/CakeCMS/Core".
13
 * @author    Sergey Kalistratov <[email protected]>
14
 */
15
16
namespace Core\Controller\Component;
17
18
use Cake\ORM\Table;
19
use JBZoo\Data\Data;
20
use JBZoo\Data\JSON;
21
use JBZoo\Utils\Arr;
22
use JBZoo\Utils\Str;
23
use Cake\Utility\Hash;
24
use Cake\Utility\Inflector;
25
use Core\Event\EventManager;
26
27
/**
28
 * Class ProcessComponent
29
 *
30
 * @package Core\Controller\Component
31
 * @property FlashComponent $Flash
32
 */
33
class ProcessComponent extends AppComponent
34
{
35
36
    const PRIMARY_KEY = 'id';
37
    const EVENT_NAME_BEFORE = 'Before';
38
    const EVENT_NAME_AFTER = 'After';
39
40
    /**
41
     * Other Components this component uses.
42
     *
43
     * @var array
44
     */
45
    public $components = [
46
        'Core.Flash'
47
    ];
48
49
    /**
50
     * Get actual request vars for process.
51
     *
52
     * @param string $name
53
     * @param string $primaryKey
54
     * @return array
55
     */
56
    public function getRequestVars($name, $primaryKey = self::PRIMARY_KEY)
57
    {
58
        $name = Str::low(Inflector::singularize($name));
59
        $requestIds = (array) $this->request->data($name);
60
        $action = $this->request->data('action');
61
        $ids = $this->_getIds($requestIds, $primaryKey);
62
63
        return [$action, $ids];
64
    }
65
66
    /**
67
     * Constructor hook method.
68
     *
69
     * @param array $config
70
     * @return void
71
     */
72
    public function initialize(array $config)
73
    {
74
        $_config = [
75
            'context'  => __d('core', 'record'),
76
            'redirect' => [
77
                'action'     => 'index',
78
                'prefix'     => $this->request->param('prefix'),
79
                'plugin'     => $this->request->param('plugin'),
80
                'controller' => $this->request->param('controller'),
81
            ],
82
            'messages' => [
83
                'no_action' => __d('core', 'Action not found.'),
84
                'no_choose' => __d('core', 'Please choose only one item.'),
85
            ]
86
        ];
87
88
        $config = Hash::merge($_config, $config);
89
        $this->config($config);
90
91
        parent::initialize($config);
92
    }
93
94
    /**
95
     * Make process.
96
     *
97
     * @param Table $table
98
     * @param string $action
99
     * @param array $ids
100
     * @param array $options
101
     * @return \Cake\Network\Response|null
102
     */
103
    public function make(Table $table, $action, array $ids = [], array $options = [])
104
    {
105
        $count       = count($ids);
106
        $options     = $this->_getOptions($options, $count);
107
        $redirectUrl = $options['redirect'];
108
        $messages    = new JSON($options['messages']);
109
110
        $event = EventManager::trigger($this->_getEventName($action), $this->_controller, ['ids' => $ids]);
111
        $ids   = $event->data->get('ids', $ids);
112
        $count = count($ids);
113
114
        if (!$action) {
115
            $this->Flash->error($messages->get('no_action'));
116
            return $this->_controller->redirect($redirectUrl);
117
        }
118
119
        if ($count <= 0) {
120
            $this->Flash->error($messages->get('no_choose'));
121
            return $this->_controller->redirect($redirectUrl);
122
        }
123
124
        $this->_loadBehavior($table);
125
        if ($table->process($action, $ids)) {
0 ignored issues
show
Bug introduced by
The method process() does not exist on Cake\ORM\Table. Did you maybe mean _processDelete()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
126
            return $this->_process($action, $messages, $redirectUrl, $ids);
127
        }
128
129
        $this->Flash->error(__d('core', 'An error has occurred. Please try again.'));
130
        return $this->_controller->redirect($redirectUrl);
131
    }
132
133
    /**
134
     * Setup default action messages.
135
     *
136
     * @param int $count
137
     * @return array
138
     */
139
    protected function _getDefaultMessages($count)
140
    {
141
        $context       = $this->_configRead('context');
142
        $contextPlural = Inflector::pluralize($context);
143
        $countString   = sprintf('<strong>%s</strong>', $count);
144
        return [
145
            'delete' => __dn(
146
                'core',
147
                'One ' . $context . ' success removed',
148
                '{0} ' . $contextPlural . ' success removed',
149
                $count,
150
                $countString
151
            ),
152
            'publish' => __dn(
153
                'core',
154
                'One ' . $context . ' success publish',
155
                '{0} ' . $contextPlural . ' success published',
156
                $count,
157
                $countString
158
            ),
159
            'unpublish' => __dn(
160
                'core',
161
                'One ' . $context . ' success unpublish',
162
                '{0} ' . $contextPlural . ' success unpublished',
163
                $count,
164
                $countString
165
            ),
166
        ];
167
    }
168
169
    /**
170
     * Get event name by data.
171
     *
172
     * @param string $action
173
     * @param string $event
174
     * @return string
175
     */
176
    protected function _getEventName($action, $event = self::EVENT_NAME_BEFORE)
177
    {
178
        $details = [];
179
        if ($prefix = $this->request->param('prefix')) {
180
            $details[] = ucfirst($prefix);
181
        }
182
183
        $details = Hash::merge($details, [
184
            'Controller',
185
            $this->_controller->name,
186
            $event . Inflector::camelize($action),
187
            'Process',
188
        ]);
189
190
        return implode('.', $details);
191
    }
192
193
    /**
194
     * Get ids by request.
195
     *
196
     * @param array $ids
197
     * @param string $primaryKey
198
     * @return array
199
     */
200
    protected function _getIds(array $ids, $primaryKey = self::PRIMARY_KEY)
201
    {
202
        $return = [];
203
        foreach ($ids as $id => $value) {
204
            if (is_array($value) && is_int($id) && (int) $value[$primaryKey] === 1) {
205
                $return[$id] = $id;
206
            }
207
        }
208
209
        return $return;
210
    }
211
212
    /**
213
     * Create and merge actual process options.
214
     *
215
     * @param array $options
216
     * @param int|string $count
217
     * @return array
218
     */
219
    protected function _getOptions(array $options, $count)
220
    {
221
        $options = Hash::merge($this->_config, $options);
222
        return Hash::merge(['messages' => $this->_getDefaultMessages($count)], $options);
223
    }
224
225
    /**
226
     * Load process behavior.
227
     *
228
     * @param Table $table
229
     */
230
    protected function _loadBehavior(Table $table)
231
    {
232
        $behaviors = $table->behaviors();
233
        if (!Arr::in('Process', $behaviors->loaded())) {
234
            $behaviors->load('Core.Process');
235
        }
236
    }
237
238
    /**
239
     * Controller process.
240
     *
241
     * @param string $action
242
     * @param Data $messages
243
     * @param array $redirect
244
     * @param array $ids
245
     * @return \Cake\Network\Response|null
246
     */
247
    protected function _process($action, Data $messages, array $redirect, array $ids)
248
    {
249
        $count = count($ids);
250
        $defaultMsg = __dn(
251
            'core',
252
            'One record success processed',
253
            '{0} records processed',
254
            $count,
255
            sprintf('<strong>%s</strong>', $count)
256
        );
257
258
        EventManager::trigger($this->_getEventName($action, self::EVENT_NAME_AFTER), $this->_controller, [
259
            'ids' => $ids
260
        ]);
261
262
        $this->Flash->success($messages->get($action, $defaultMsg));
263
        return $this->_controller->redirect($redirect);
264
    }
265
}
266