Completed
Branch dev (869f5d)
by
unknown
04:25
created

AdminPageFramework_Form___SubmitNotice::render()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 19
Code Lines 8

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 19
rs 9.2
cc 4
eloc 8
nc 3
nop 0
1
<?php
2
/**
3
 * Admin Page Framework
4
 * 
5
 * http://en.michaeluno.jp/admin-page-framework/
6
 * Copyright (c) 2013-2016 Michael Uno; Licensed MIT
7
 * 
8
 */
9
10
/**
11
 * Provides methods to handle setting notices.
12
 * 
13
 * @package     AdminPageFramework
14
 * @subpackage  Form
15
 * @since       3.7.0
16
 * @extends     AdminPageFramework_FrameworkUtility
17
 */
18
class AdminPageFramework_Form___SubmitNotice extends AdminPageFramework_FrameworkUtility {
19
    
20
    /**
21
     * Stores form submit notifications.
22
     * 
23
     * At the script termination, these will be saved as a transient in the database.
24
     */
25
    static private $_aNotices = array();
26
    
27
    public $sTransientKey;
28
    
29
    /**
30
     * Sets up properties.
31
     */
32
    public function __construct() {
33
        
34
        $this->sTransientKey = $this->_getTransientKey();
35
        
36
    }
37
        /**
38
         * @remark      Up to 40 chars
39
         * @remark      Not using the page-now value nor page slug because the user may be redirected to a different page.
40
         * @return      string
41
         */
42
        private function _getTransientKey() {
43
            return 'apf_ntc_' . get_current_user_id();
44
        }
45
    
46
    /**
47
     * Checks if a submit notice has been set in the current screen (not in the database).
48
     * 
49
     * This is used in the internal validation callback method to decide whether the system error or update notice should be added or not.
50
     * If this method yields true, the framework discards the system message and displays the user set notification message.
51
     * 
52
     * @param       string      $sType If empty, the method will check if a message exists in all types. Otherwise, it checks the existence of a message of the specified type.
53
     * @return      boolean     True if a setting notice is set; otherwise, false.
54
     */
55
    public function hasNotice( $sType='' ) {
56
                
57
        if ( ! $sType ) {
58
            return ( boolean ) count( self::$_aNotices );
59
        }
60
        
61
        // Check if there is a message of the type.
62
        foreach( self::$_aNotices as $_aNotice ) {
63
            $_sClassAttribute = $this->getElement( 
64
                $_aNotice, 
65
                array( 
66
                    'aAttributes', 
67
                    'class' 
68
                ),
69
                ''
70
            );
71
            if ( $_sClassAttribute === $sType ) {
72
                return true;
73
            }
74
        }
75
        return false;
76
        
77
    }
78
    
79
    /**
80
     * Sets the given message to be displayed in the next page load. 
81
     * 
82
     * This is used to inform users about the submitted input data, such as "Updated successfully." or "Problem occurred." etc. 
83
     * and normally used in validation callback methods.
84
     * 
85
     * <h4>Example</h4>
86
     * `
87
     * if ( ! $bVerified ) {
88
     *       $this->setFieldErrors( $aErrors );     
89
     *       $this->setSettingNotice( 'There was an error in your input.' );
90
     *       return $aOldPageOptions;
91
     * }
92
     * `
93
     * @since        3.7.0
94
     * @access       public
95
     * @param        string      $sMessage       the text message to be displayed.
96
     * @param        string      $sType          (optional) the type of the message, either "error" or "updated"  is used.
97
     * @param        array       $asAttributes   (optional) the tag attribute array applied to the message container HTML element. If a string is given, it is used as the ID attribute value.
98
     * @param        boolean     $bOverride      (optional) If true, only one message will be shown in the next page load. false: do not override when there is a message of the same id. true: override the previous one.
99
     * @return       void
100
     */
101
    public function set( $sMessage, $sType='error', $asAttributes=array(), $bOverride=true ) {
102
        
103
        // If the array is empty, schedule the task of saving the array at shutdown.
104
        if ( empty( self::$_aNotices ) ) {
105
            add_action( 'shutdown', array( $this, '_replyToSaveNotices' ) ); // the method is defined in the model class.
106
        }
107
        
108
        $_sID = md5( trim( $sMessage ) );
109
            
110
        // If the override is false and a message is already set, do not add.
111
        if ( ! $bOverride && isset( self::$_aNotices[ $_sID ] ) ) {
112
            return;
113
        }
114
115
        // If the override is true, reset the notice array.
116
        if ( $bOverride ) {
117
            self::$_aNotices = array();
118
        }
119
        
120
        $_aAttributes = $this->getAsArray( $asAttributes );
121
        if ( is_string( $asAttributes ) && ! empty( $asAttributes ) ) {
122
            $_aAttributes[ 'id' ] = $asAttributes;
123
        }
124
        self::$_aNotices[ $_sID ] = array(
125
            'sMessage'      => $sMessage,
126
            'aAttributes'   => $_aAttributes + array(
127
                'class'     => $sType,
128
                'id'        => 'form_submit_notice_' . $_sID,
129
            ),
130
        );
131
132
133
    }       
134
        /**
135
         * Saves the notification array set via the setSettingNotice() method.
136
         * 
137
         * @since       3.0.4 
138
         * @sine        3.7.0      Moved from `AdminPageFramework_Factory_Model`.
139
         * @internal
140
         * @callback    action     shutdown
141
         * @return      void
142
         */
143
        public function _replyToSaveNotices() {
144
            if ( empty( self::$_aNotices ) ) { 
145
                return; 
146
            }            
147
            $_bResult = $this->setTransient( 
0 ignored issues
show
Unused Code introduced by
$_bResult 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...
148
                $this->sTransientKey, 
149
                self::$_aNotices
150
            );
151
        }        
152
    
153
    /**
154
     * Outputs the stored submit notices in the database.
155
     * @return      void
156
     */
157
    public function render() {
0 ignored issues
show
Coding Style introduced by
render uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
158
159
        // This will load scripts for the fade-in effect.
160
        new AdminPageFramework_AdminNotice( '' );
161
        
162
        // Retrieve the notifications set in a transient.
163
        $_aNotices = $this->_getNotices();
164
        if ( false === $_aNotices ) { 
165
            return; 
166
        }
167
            
168
        // By setting false to the 'settings-notice' key, it's possible to disable the notifications set with the framework.
169
        if ( isset( $_GET[ 'settings-notice' ] ) && ! $_GET[ 'settings-notice' ] ) { 
170
            return; 
171
        }
172
            
173
        $this->_printNotices( $_aNotices );                
174
        
175
    }
176
        /**
177
         * @since       3.7.8
178
         * @return      array|boolean
179
         */
180
        private function _getNotices() {
181
        
182
            if ( isset( self::$_aNoticeCaches[ $this->sTransientKey ] ) ) {
183
                return self::$_aNoticeCaches[ $this->sTransientKey ];
184
            }
185
186
            $_abNotices = $this->getTransient( $this->sTransientKey );            
187
            if ( false !== $_abNotices ) {
188
                $this->deleteTransient( $this->sTransientKey );
189
            }
190
191
            self::$_aNoticeCaches[ $this->sTransientKey ] = $_abNotices;
192
            return self::$_aNoticeCaches[ $this->sTransientKey ];
193
            
194
        }
195
            static private $_aNoticeCaches = array();
196
            
197
        /**
198
         * Displays settings notices.
199
         * @since       3.5.3
200
         * @since       3.7.0      Moved from `AdminPageFramework_Factory_View`. Renamed from `_printSettingNotices()`.
201
         * @internal
202
         * @return      void
203
         */
204
        private function _printNotices( $aNotices ) {
205
            
206
            $_aPeventDuplicates = array();
207
            foreach ( array_filter( ( array ) $aNotices, 'is_array' ) as $_aNotice ) {
208
                
209
                $_sNotificationKey = md5( serialize( $_aNotice ) );
210
                if ( isset( $_aPeventDuplicates[ $_sNotificationKey ] ) ) {
211
                    continue;
212
                }
213
                $_aPeventDuplicates[ $_sNotificationKey ] = true;
214
                
215
                new AdminPageFramework_AdminNotice(
216
                    $this->getElement( $_aNotice, 'sMessage' ),
217
                    $this->getElement( $_aNotice, 'aAttributes' )
218
                );              
219
              
220
            }            
221
            
222
        }    
223
        
224
}
225