WizflowManager.php 9.86 KB
Newer Older
Marcello Pivanti's avatar
Marcello Pivanti committed
1
<?php
Aster's avatar
Aster committed
2

Marcello Pivanti's avatar
Marcello Pivanti committed
3
/**
Aster's avatar
Aster committed
4
5
 * Lombardia Informatica S.p.A.
 * OPEN 2.0
Marcello Pivanti's avatar
Marcello Pivanti committed
6
 *
Aster's avatar
Aster committed
7
 * @see http://example.com Developers'community
8
9
 * @license GPLv3
 * @license https://opensource.org/licenses/gpl-3.0.html GNU General Public License version 3
Marcello Pivanti's avatar
Marcello Pivanti committed
10
 *
Aster's avatar
Aster committed
11
 * @package    elitedivision\amos\wizflow
Marcello Pivanti's avatar
Marcello Pivanti committed
12
 * @category   CategoryName
Aster's avatar
Aster committed
13
 * @author     Lombardia Informatica S.p.A.
Marcello Pivanti's avatar
Marcello Pivanti committed
14
15
 */

Aster's avatar
Aster committed
16
namespace elitedivision\amos\wizflow;
Marcello Pivanti's avatar
Marcello Pivanti committed
17
18
19
20
21
22
23
24
25
26
27

use raoul2000\workflow\base\Status;
use raoul2000\workflow\source\IWorkflowSource;
use Yii;
use yii\base\Exception;
use yii\base\InvalidConfigException;
use yii\base\Model;

/**
 * Class WizflowManager
 * Implement the Wizard UI design pattern using yii2-workflow.
Aster's avatar
Aster committed
28
 * @package elitedivision\amos\wizflow
Marcello Pivanti's avatar
Marcello Pivanti committed
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
 */
class WizflowManager extends \yii\base\BaseObject
{
    /**
     * @var array SimpleWorkflowBehavior configuration array attached to all wizard steps
     */
    public $workflowBehavior = [
        'class' => '\raoul2000\workflow\base\SimpleWorkflowBehavior',
        'defaultWorkflowId' => 'Wizflow'
    ];

    /**
     * @var string name of the workflow
     */
    public $workflowName = '';

    /**
     * @var string name of the workflow behavior that is attached to all wizards steps
     */
    public $workflowBehaviorName = 'wizflowBehavior';

    /**
     * @var string Name of the workflow source component to use
     */
    public $workflowSourceName = 'workflowSource';

    /**
     * @var IWorkflowSource the workflow source instance
     */
    private $_ws;

    /**
     * @var string session key name used to store steps
     */
    public $skeyName = '_wiz';

    /**
     * This array stores the wizards state :
     * - the current step (key = 'current')
     * - a list of all steps that have been performed so far (key = 'path')
     *
     * Example :
     * <pre>
     * [
     *        'current' => [
     *            'attrib1' => 'value1',
     *            //...
     *            'status'     => 'Wizflow/step',
     *        ],
     *        'path' => [
     *            'Wizflow/step' => [
     *                'attrib1' => 'value1',
     *                //...
     *                'status'     => 'Wizflow/step',
     *            ],
     *            //etc ...
     *        ]
     * ]
     *</pre>
     */
    private $_wiz = [
        'current' => null,
        'path' => []
    ];

    /**
     * Loads existing wizard data if available.
     *
     * @see \yii\base\Object::init()
     */
    public function init()
    {
        if (empty($this->skeyName) || !is_string($this->skeyName)) {
            throw new InvalidConfigException('Parameter "skeyName" must be a non-empty string');
        }

        if (empty($this->workflowSourceName) || !is_string($this->workflowSourceName)) {
            throw new InvalidConfigException('Parameter "workflowSourceName" must be a non-empty string');
        }

        $this->_ws = Yii::$app->get($this->getWorkflowSourceName());

        $wiz = Yii::$app->session->get($this->skeyName, null);
        if ($wiz !== null) {
            $this->_wiz = $wiz;
        }
    }

    /**
     * Returns the name workflow source component to use.
     * Note that the component must be available and registred in the Yii::$app container.
     *
     * @return string The name of the workflow source component
     */
    public function getWorkflowSourceName()
    {
        return $this->workflowSourceName;
    }

    /**
     * Returns the workflow source component used by the manager
     * @return IWorkflowSource the workflow source component instance
     */
    public function getWorkflowSource()
    {
        return $this->_ws;
    }

    /**
     * Creates and returns the form model instance for the status attribute.
     * Note that the attribute array passed as argument must include the status value.
     *
     * The instance is created using the 'model' metadata value associated with the 'status'
     * attribute value. The metadata 'model' must be an array suitable to invoke Yii::createObject().
     *
     * Once created, the SimpleWorkflowBehavior is attached to the model.
     *
     * @param array $attributes list of attributes
     * @throws Exception
     * @return Model
     */
    private function createInstance($attributes)
    {
        if (isset($attributes['status']) == false) {
            throw new Exception('missing attribute "status"');
        }

        /** @var Status $status */
        $status = $this->workflowSource->getStatus($attributes['status']);

        $metaModel = $status->getMetadata('model');
        if (is_string($metaModel)) {
            $modelData['class'] = $metaModel;
        } else {
            $modelData = $metaModel;
        }

        $config = array_merge(
            $modelData,
            $attributes
        );
        /** @var Model $instance */
        $instance = Yii::createObject($config);
        $instance->attachBehavior(
            $this->workflowBehaviorName,
            [
                'class' => '\raoul2000\workflow\base\SimpleWorkflowBehavior',
                'defaultWorkflowId' => $this->workflowName
            ]
        );

        return $instance;
    }

    /**
     * Save the wizard data into the current session
     */
    public function save()
    {
        Yii::$app->session->set($this->skeyName, $this->_wiz);
    }

    /**
     * @return boolean TRUE if the wizard process as started (i.e. a current step is available)
     * FALSE otherwise.
     */
    public function hasCurrentStep()
    {
        return $this->_wiz['current'] != null;
    }

    /**
     * Updates the current step with the model passed as argument.
     *
     * @param Model $model
     * @throws Exception
     */
    public function updateCurrentStep($model)
    {
        if ($this->hasCurrentStep() == false) {
            throw new Exception('wizard has no current step');
        }
        $this->_wiz['current'] = $model->getAttributes();
    }

    /**
     * Returns the model associated with the current wizard step.
     *
     * @return Model|null the current step model instance or NULL if no current step is defined.
     */
    public function getCurrentStep()
    {
        $currentStep = null;
        if ($this->hasCurrentStep()) {
            $currentStep = $this->createInstance($this->_wiz['current']);
        }
        return $currentStep;
    }

    /**
     * Returns an array containing all steps models that have been done until now.
     * The current step is not included in the returned array.
     *
     * @return array list of steps that have been performed until now
     */
    public function getPath()
    {
        $path = [];
        foreach ($this->_wiz['path'] as $stepConfig) {
            $stepModel = $this->createInstance($stepConfig);
            $path[] = $stepModel;
        }
        return $path;
    }

    /**
     * Add the current step to the path and creates the next step form which becomes the new current step.
     *
     * @return Model the new current step
     */
    public function getNextStep()
    {
        $nextStep = null;
        if ($this->hasCurrentStep()) {
            // add current step to the path

            $currentStep = $this->getCurrentStep();
            $this->_wiz['path'][$currentStep->getWorkflowStatus()->getId()] = $this->_wiz['current'];
            $this->_wiz['current'] = null;

            // find the next step

            $nextStatuses = $currentStep->getNextStatuses(true, true);
            $nextStep = null;
            if (count($nextStatuses) != 0) {
                foreach ($nextStatuses as $info) {
                    if ($info['isValid']) {
                        /** @var Status $status */
                        $status = $info['status'];
                        // create the next step Form instance
                        $nextStep = $this->createInstance(['status' => $status->getId()]);

                        // save it as the current step
                        $this->_wiz['current'] = $nextStep->getAttributes();

                        break;
                    }
                }
            }
        }
        return $nextStep;
    }

    /**
     * Replace the current step, with the last step of the path and returns it.
     *
     * @return Model the new current step
     */
    public function getPreviousStep()
    {
        $prevStep = null;
        if (count($this->_wiz['path']) != 0) {

            $config = array_pop($this->_wiz['path']);

            // replace current step
            $this->_wiz['current'] = $config;

            // create instance
            $prevStep = $this->createInstance($config);
        }
        return $prevStep;
    }

    /**
     * Initiate the wizard.
     * This method reset the existing wizard path and returns the model for the first step.
     *
     * @return Model the model for the first step
     */
    public function start()
    {
        $workflow = $this->workflowSource->getWorkflow($this->workflowName);

        /** @var Status $status */
        $status = $workflow->getInitialStatus();

        $metaModel = $status->getMetadata('model');
        if (is_string($metaModel)) {
            $config['class'] = $metaModel;
        } else {
            $config = $metaModel;
        }
        $config['status'] = $status->getId();

        $firstStep = $this->createInstance($config);

        $this->_wiz['current'] = $firstStep->getAttributes();
        $this->_wiz['path'] = [];

        return $firstStep;
    }

    /**
     * Clean up session data that may have been stored by this wizard.
     */
    public function destroy()
    {
        Yii::$app->session->remove($this->skeyName);
    }

    /**
     * Retrieve a data saved in session
     *
     * example: getSavedModel('Workflow/STEP3')
     * @param $workFlowId
     * @return null, Model data
     */
    public function getSavedModel($workFlowId)
    {
        $path = Yii::$app->session->get($this->skeyName)['path'];
        $model = null;
        if (isset($path[$workFlowId])) {
            $model = $path[$workFlowId];
        }
        return $model;
    }
}