Completed
Push — master ( ba2d6c...6cc24f )
by Mark
21s
created

FlashComponent::getSession()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
4
 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
5
 *
6
 * Licensed under The MIT License
7
 * For full copyright and license information, please see the LICENSE.txt
8
 * Redistributions of files must retain the above copyright notice.
9
 *
10
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
11
 * @link          https://cakephp.org CakePHP(tm) Project
12
 * @since         3.0.0
13
 * @license       https://opensource.org/licenses/mit-license.php MIT License
14
 */
15
namespace Cake\Controller\Component;
16
17
use Cake\Controller\Component;
18
use Cake\Controller\ComponentRegistry;
19
use Cake\Http\Exception\InternalErrorException;
20
use Cake\Utility\Inflector;
21
use Exception;
22
23
/**
24
 * The CakePHP FlashComponent provides a way for you to write a flash variable
25
 * to the session from your controllers, to be rendered in a view with the
26
 * FlashHelper.
27
 *
28
 * @method void success(string $message, array $options = []) Set a message using "success" element
29
 * @method void error(string $message, array $options = []) Set a message using "error" element
30
 */
31
class FlashComponent extends Component
32
{
33
34
    /**
35
     * The Session object instance
36
     *
37
     * @var \Cake\Http\Session
38
     * @deprecated 3.7.5 This property will be removed in 4.0.0 in favor of `getSession()` method.
39
     */
40
    protected $_session;
41
42
    /**
43
     * Default configuration
44
     *
45
     * @var array
46
     */
47
    protected $_defaultConfig = [
48
        'key' => 'flash',
49
        'element' => 'default',
50
        'params' => [],
51
        'clear' => false,
52
        'duplicate' => true
53
    ];
54
55
    /**
56
     * Constructor
57
     *
58
     * @param \Cake\Controller\ComponentRegistry $registry A ComponentRegistry for this component
59
     * @param array $config Array of config.
60
     */
61
    public function __construct(ComponentRegistry $registry, array $config = [])
62
    {
63
        parent::__construct($registry, $config);
64
        $this->_session = $registry->getController()->getRequest()->getSession();
0 ignored issues
show
Deprecated Code introduced by
The property Cake\Controller\Componen...ashComponent::$_session has been deprecated with message: 3.7.5 This property will be removed in 4.0.0 in favor of `getSession()` method.

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
65
    }
66
67
    /**
68
     * Used to set a session variable that can be used to output messages in the view.
69
     * If you make consecutive calls to this method, the messages will stack (if they are
70
     * set with the same flash key)
71
     *
72
     * In your controller: $this->Flash->set('This has been saved');
73
     *
74
     * ### Options:
75
     *
76
     * - `key` The key to set under the session's Flash key
77
     * - `element` The element used to render the flash message. Default to 'default'.
78
     * - `params` An array of variables to make available when using an element
79
     * - `clear` A bool stating if the current stack should be cleared to start a new one
80
     * - `escape` Set to false to allow templates to print out HTML content
81
     *
82
     * @param string|\Exception $message Message to be flashed. If an instance
83
     *   of \Exception the exception message will be used and code will be set
84
     *   in params.
85
     * @param array $options An array of options
86
     * @return void
87
     */
88
    public function set($message, array $options = [])
89
    {
90
        $options += (array)$this->getConfig();
91
92
        if ($message instanceof Exception) {
93
            if (!isset($options['params']['code'])) {
94
                $options['params']['code'] = $message->getCode();
95
            }
96
            $message = $message->getMessage();
97
        }
98
99
        if (isset($options['escape']) && !isset($options['params']['escape'])) {
100
            $options['params']['escape'] = $options['escape'];
101
        }
102
103
        list($plugin, $element) = pluginSplit($options['element']);
104
105
        if ($plugin) {
106
            $options['element'] = $plugin . '.Flash/' . $element;
107
        } else {
108
            $options['element'] = 'Flash/' . $element;
109
        }
110
111
        $messages = [];
112
        if (!$options['clear']) {
113
            $messages = (array)$this->getSession()->read('Flash.' . $options['key']);
114
        }
115
116
        if (!$options['duplicate']) {
117
            foreach ($messages as $existingMessage) {
118
                if ($existingMessage['message'] === $message) {
119
                    return;
120
                }
121
            }
122
        }
123
124
        $messages[] = [
125
            'message' => $message,
126
            'key' => $options['key'],
127
            'element' => $options['element'],
128
            'params' => $options['params']
129
        ];
130
131
        $this->getSession()->write('Flash.' . $options['key'], $messages);
132
    }
133
134
    /**
135
     * Magic method for verbose flash methods based on element names.
136
     *
137
     * For example: $this->Flash->success('My message') would use the
138
     * success.ctp element under `src/Template/Element/Flash` for rendering the
139
     * flash message.
140
     *
141
     * If you make consecutive calls to this method, the messages will stack (if they are
142
     * set with the same flash key)
143
     *
144
     * Note that the parameter `element` will be always overridden. In order to call a
145
     * specific element from a plugin, you should set the `plugin` option in $args.
146
     *
147
     * For example: `$this->Flash->warning('My message', ['plugin' => 'PluginName'])` would
148
     * use the warning.ctp element under `plugins/PluginName/src/Template/Element/Flash` for
149
     * rendering the flash message.
150
     *
151
     * @param string $name Element name to use.
152
     * @param array $args Parameters to pass when calling `FlashComponent::set()`.
153
     * @return void
154
     * @throws \Cake\Http\Exception\InternalErrorException If missing the flash message.
155
     */
156
    public function __call($name, $args)
157
    {
158
        $element = Inflector::underscore($name);
159
160
        if (count($args) < 1) {
161
            throw new InternalErrorException('Flash message missing.');
162
        }
163
164
        $options = ['element' => $element];
165
166
        if (!empty($args[1])) {
167
            if (!empty($args[1]['plugin'])) {
168
                $options = ['element' => $args[1]['plugin'] . '.' . $element];
169
                unset($args[1]['plugin']);
170
            }
171
            $options += (array)$args[1];
172
        }
173
174
        $this->set($args[0], $options);
175
    }
176
177
    /**
178
     * Returns current session object from a controller request.
179
     *
180
     * @return \Cake\Http\Session
181
     */
182
    protected function getSession()
183
    {
184
        return $this->getController()->getRequest()->getSession();
185
    }
186
}
187