├── .gitignore ├── LICENSE ├── README.md ├── Y.php └── composer.json /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .DS_Store 3 | composer.phar 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2010-2013, Leonid Svyatov 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | * redistributions of source code must retain the above copyright notice, this list 7 | of conditions and the following disclaimer. 8 | * redistributions in binary form must reproduce the above copyright notice, this 9 | list of conditions and the following disclaimer in the documentation and/or 10 | other materials provided with the distribution. 11 | * no names of contributors may be used to endorse or promote products derived from 12 | this software without specific prior written permission. 13 | 14 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 15 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 16 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 17 | DISCLAIMED. IN NO EVENT SHALL {{THE COPYRIGHT HOLDER OR CONTRIBUTORS}} BE LIABLE 18 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 19 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 20 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 21 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR 22 | TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 23 | THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Y 2 | = 3 | 4 | Shortcuts for [Yii framework](http://www.yiiframework.com) v1.1 5 | 6 | 7 | Install 8 | ------- 9 | 10 | ### via Composer (recommended) 11 | 12 | `php composer.phar require svyatov/yii-shortcut '~2.0'` 13 | 14 | ### via download 15 | 16 | Get the [latest release](https://github.com/svyatov/Yii-shortcut/releases) and put `Y.php` file in your application `protected/components` folder. 17 | 18 | 19 | Usage 20 | ----- 21 | 22 | #### Creating URL by route in a widget 23 | 24 | ```php 25 | // Standart code 26 | Yii::app()->controller->createUrl('user/login'); 27 | 28 | // Y code 29 | Y::url('user/login'); 30 | ``` 31 | 32 | #### Get/set some cache value 33 | 34 | ```php 35 | // Standart code 36 | Yii::app()->cache->get('user_settings'); 37 | Yii::app()->cache->set('user_settings', $userSettings); 38 | 39 | // Y code 40 | Y::getCache('user_settings'); 41 | Y::setCache('user_settings', $userSettings); 42 | ``` 43 | 44 | #### The same with cookies 45 | 46 | ```php 47 | // Y code 48 | Y::getCookie('user_settings'); 49 | Y::setCookie('user_settings', $userSettings); 50 | ``` 51 | 52 | 53 | #### Getting the value of CSRF token 54 | 55 | ```php 56 | // Standart code 57 | Yii::app()->request->csrfToken; 58 | 59 | // Y code 60 | Y::csrf(); 61 | ``` 62 | 63 | #### Inserting CSRF name and token in some jQuery request 64 | 65 | ```phtml 66 | // Standart code 67 | 70 | 71 | // Y code 72 | 75 | ``` 76 | 77 | #### Quick variable dump with code highlighting 78 | 79 | ```php 80 | // Standart code 81 | echo '
'; 82 | CVarDumper::dump($testVariable, 10, true); 83 | Yii::app()->end(); 84 | 85 | // Y code 86 | Y::dump($testVariable); 87 | ``` 88 | 89 | #### Short action ending without template rendering (e.g. for AJAX requests) 90 | 91 | ```php 92 | // Standart code 93 | echo $result; 94 | Yii::app()->end(); 95 | // or 96 | echo json_encode($result); 97 | Yii::app()->end(); 98 | 99 | // Y code 100 | Y::end($result); 101 | // or 102 | Y::endJson($result); 103 | ``` 104 | 105 | #### Redirects 106 | 107 | ```php 108 | // Standart code 109 | $this->redirect($this->createUrl('user/settings')); // the shortest example 110 | Yii::app()->request->redirect(Yii::app()->controller->createUrl('user/settings')); // if we inside some widget 111 | 112 | // Y code 113 | Y::redirect('user/settings'); // you can use wherever you want, controller/widget, it doesn't matter 114 | ``` 115 | 116 | #### Detecting current user status (is he a guest or is he authenticated) 117 | 118 | ```php 119 | // Standart code 120 | if (Yii::app()->user->isGuest) {} // is user a guest? 121 | // or 122 | if (!Yii::app()->user->isGuest) {} // is user authenticated? 123 | 124 | // Y code 125 | if (Y::isGuest()) {} // is user a guest? 126 | // or 127 | if (Y::isAuthenticated()) {} // is user authenticated? 128 | // the code speaks for himself, it's more expressive and readable 129 | ``` 130 | 131 | As you can see, the amount of code becomes at least 2 times smaller. So you need to type at least 2 times less and you can read it and understand it at least 2 times faster. 132 | 133 | 134 | Changelog 135 | --------- 136 | 137 | * **v2.0.0** / 26.08.2014 138 | 139 | `new` Added new methods: module() and component(). 140 | 141 | `chg` Removed protected method _getComponent(). 142 | 143 | `chg` Removed method getRequest(). 144 | 145 | `chg` Protected method _getValueByComplexKeyFromArray() renamed to getValueByComplexKeyFromArray() and changed to public. 146 | 147 | `chg` Methods getGet(), getPost() and getFiles() renamed to GET(), POST() and FILES() respectively. 148 | 149 | `chg` Method isAuthed() renamed to isAuthenticated(). 150 | 151 | `chg` Method redir() renamed to redirect(). 152 | 153 | `chg` Method flashRedir() renamed to flashAndRedirect(). 154 | 155 | `chg` Methods redirAuthed() and redirGuest() renamed to redirectIfAuthenticated() and redirectIfGuest() respectively. 156 | 157 | `chg` Method hasAccess() renamed to checkAccess(). 158 | 159 | `chg` Setters, getters and deleters for cache, cookie and session renamed to comply common pattern, e.g.: cacheSet() -> setCache(). 160 | 161 | 162 | * **v1.3.2** / 05.05.2014 163 | 164 | `fix` Composer autoloading fixed. 165 | 166 | `chg` Scope of _getComponent() and _getValueByComplexKeyFromArray() methods changed to protected. 167 | 168 | `chg` README.md enhanced and style updated. 169 | 170 | `chg` phpDoc comments light reformat. 171 | 172 | * **v1.3.1** / 28.09.2013 173 | 174 | `fix` Fixed urls to repo. No code changed. 175 | 176 | * **v1.3.0** / 12.07.2013 177 | 178 | `new` Everything is translated to English. 179 | 180 | `new` Added LICENSE file. 181 | 182 | `chg` Updated composer.json file. 183 | 184 | `chg` Added second argument $options to cookieDelete() method. 185 | 186 | `chg` Added $secure and $httpOnly arguments to cookieSet() method. Besides, $value argument could be an instance of CHttpCookie class now. 187 | 188 | `chg` CSRF token name in method csrfJsParam() now quoted. 189 | 190 | `chg` Default $message argument value in flash() method changed to 'false' so now there is a way to remove flash message by passing 'null' as $message argument. 191 | 192 | `chg` Added $params and $allowCaching arguments to hasAccess() method. It doesn't change previous behaviour but extending method abilities. 193 | 194 | `chg` Code refactoring. 195 | 196 | * **v1.2.1** / 25.01.2012 197 | 198 | `new` Added method getFile(). 199 | 200 | * **v1.2.0** / 20.10.2011 201 | 202 | `new` Added methods: format, script, session, sessionGet, sessionSet, sessionDelete. 203 | 204 | `new` Added internal caching of application components. 205 | 206 | `chg` cookieDelete() method now returns the object of removed cookie (like the original method). 207 | 208 | * **v1.1.5** / 29.09.2011 209 | 210 | `new` Added method dbCmd(). 211 | 212 | `fix` Fixed errors in @since phpDoc tags. 213 | 214 | * **v1.1.4** / 27.09.2011 215 | 216 | `fix` Fixed bug in cookieSet() method, which prevents setting cookie if there was no $expire argument. 217 | 218 | `chg` Cookie methods now use native methods of the CCookieCollection class. 219 | 220 | * **v1.1.3** / 19.07.2011 221 | 222 | `new` Added methods: getGet, getPost, getRequest, getPdo, hasFlash. 223 | 224 | `chg` cache(), cacheDelete(), cacheGet(), cacheSet() methods now have $cacheId argument, which gives the ability to select different cache backends. 225 | 226 | `chg` Added $options argument to endJson() method, which gives the ability to pass options to native json_encode() function. 227 | 228 | `chg` More "magic" removed. Code refactoring. 229 | 230 | * **v1.1.0** / 29.05.2011 231 | 232 | `new` Added methods: isAjaxRequest, isPutRequest, isDeleteRequest, isPostRequest, isSecureConnection. 233 | 234 | `new` Added changelog to README. README.markdown renamed to README.md 235 | 236 | `chg` Removed almost every "magic" inside methods. 237 | 238 | `chg` Added $absolute argument to baseUrl() method, which gives the ability to get absolute URL instead of relative one. 239 | 240 | `chg` Added $default argument to cookieGet() method, which gives the ability to return value of $default variable if cookie with specified name doesn't exist. 241 | 242 | `chg` Added $default argument to param() method, which gives the ability to return value of $default variable if parameter with specified name doesn't exist. Also, method code refactored. 243 | 244 | `chg` Fixed and enhanced phpDoc comments. 245 | 246 | * **v1.0.4** / 05.01.2011 247 | 248 | `chg` Code refactoring. Class uploaded to GitHub. 249 | 250 | * **v1.0.3** / 16.12.2010 251 | 252 | `fix` Fixed bug in param() method. 253 | 254 | * **v1.0.2** / 16.12.2010 255 | 256 | `new` Added method hasAccess(). 257 | 258 | `new` Enhanced method param(). Now key could contain dot delimited string to access nested variables. For example: 'site.title' returns value at param['site']['title']. Thanks for idea to sergebezborodov. 259 | 260 | `chg` Code refactoring. 261 | -------------------------------------------------------------------------------- /Y.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2010-2014, Leonid Svyatov 8 | * @license BSD-3-Clause 9 | * @version 2.0.0 10 | * @link https://github.com/svyatov/Yii-shortcut 11 | */ 12 | class Y 13 | { 14 | /** 15 | * Returns application component 16 | * 17 | * @param string $moduleName application module name 18 | * @return CModule 19 | * @since 2.0.0 20 | */ 21 | public static function module($moduleName) 22 | { 23 | return Yii::app()->getModule($moduleName); 24 | } 25 | 26 | /** 27 | * Returns application component 28 | * 29 | * @param string $componentName application component name (request, db, user, etc...) 30 | * @return CComponent 31 | * @since 2.0.0 32 | */ 33 | protected static function component($componentName) 34 | { 35 | return Yii::app()->getComponent($componentName); 36 | } 37 | 38 | /** 39 | * @return CFormatter 40 | * @since 1.2.0 41 | */ 42 | public static function format() 43 | { 44 | return Yii::app()->getComponent('format'); 45 | } 46 | 47 | /** 48 | * @return CClientScript 49 | * @since 1.2.0 50 | */ 51 | public static function script() 52 | { 53 | return Yii::app()->getComponent('clientScript'); 54 | } 55 | 56 | /** 57 | * @return CHttpRequest 58 | */ 59 | public static function request() 60 | { 61 | return Yii::app()->getComponent('request'); 62 | } 63 | 64 | /** 65 | * @return CHttpSession 66 | * @since 1.2.0 67 | */ 68 | public static function session() 69 | { 70 | return Yii::app()->getComponent('session'); 71 | } 72 | 73 | /** 74 | * Returns the cache component 75 | * 76 | * @param string $cacheId ID of the cache component, defaults to 'cache' (@since 1.1.3) 77 | * @return ICache 78 | */ 79 | public static function cache($cacheId = 'cache') 80 | { 81 | return Yii::app()->getComponent($cacheId); 82 | } 83 | 84 | /** 85 | * @return CWebUser 86 | */ 87 | public static function user() 88 | { 89 | return Yii::app()->getComponent('user'); 90 | } 91 | 92 | /** 93 | * Removes a session variable 94 | * 95 | * @param string $key the name of the session variable to be removed 96 | * @return mixed the removed value, null if no such session variable 97 | * @since 1.2.0 98 | */ 99 | public static function deleteSession($key) 100 | { 101 | return Yii::app()->getComponent('session')->remove($key); 102 | } 103 | 104 | /** 105 | * Returns the session variable value or $defaultValue if the session variable does not exist 106 | * 107 | * @param string $key the session variable name 108 | * @param mixed $defaultValue the default value to be returned when the session variable does not exist 109 | * @return mixed the session variable value, or $defaultValue if the session variable does not exist 110 | * @since 1.2.0 111 | */ 112 | public static function getSession($key, $defaultValue = null) 113 | { 114 | return Yii::app()->getComponent('session')->get($key, $defaultValue); 115 | } 116 | 117 | /** 118 | * Sets a session variable 119 | * 120 | * @param string $key session variable name 121 | * @param mixed $value session variable value 122 | * @since 1.2.0 123 | */ 124 | public static function setSession($key, $value) 125 | { 126 | Yii::app()->getComponent('session')->add($key, $value); 127 | } 128 | 129 | /** 130 | * Creates and returns a DB command for execution 131 | * 132 | * @param string|array $query the DB query to be executed. This can be either a string representing a SQL statement, 133 | * or an array representing different fragments of a SQL statement. Please refer to {@link CDbCommand::__construct} 134 | * for more details about how to pass an array as the query. If this parameter is not given, you will have to call 135 | * query builder methods of {@link CDbCommand} to build the DB query. 136 | * @param string $dbId ID of the DB component, default value is 'db' 137 | * @return CDbCommand 138 | * @since 1.1.5 139 | */ 140 | public static function dbCmd($query = '', $dbId = 'db') 141 | { 142 | return Yii::app()->getComponent($dbId)->createCommand($query); 143 | } 144 | 145 | /** 146 | * Returns the $_GET variable value or $defaultValue if the $_GET variable does not exist 147 | * 148 | * @param string $name the $_GET variable name (could be used dot delimiter for nested variable) 149 | * Example: variable name 'Post.post_text' will return value at $_GET['Post']['post_text'] 150 | * @param mixed $defaultValue the default value to be returned when the $_GET variable does not exist 151 | * @return mixed 152 | * @since 1.1.2 153 | */ 154 | public static function GET($name, $defaultValue = null) 155 | { 156 | return self::getValueByComplexKeyFromArray($name, $_GET, $defaultValue); 157 | } 158 | 159 | /** 160 | * Returns the $_POST variable value or $defaultValue if the $_POST variable does not exist 161 | * 162 | * @param string $name the $_POST variable name (could be used dot delimiter for nested variable) 163 | * Example: variable name 'Post.post_text' will return value at $_POST['Post']['post_text'] 164 | * @param mixed $defaultValue the default value to be returned when the $_POST variable does not exist 165 | * @return mixed 166 | * @since 1.1.2 167 | */ 168 | public static function POST($name, $defaultValue = null) 169 | { 170 | return self::getValueByComplexKeyFromArray($name, $_POST, $defaultValue); 171 | } 172 | 173 | /** 174 | * Returns the $_FILES variable value or $defaultValue if the $_FILES variable does not exist 175 | * 176 | * @param string $name the $_FILES variable name (could be used dot delimiter for nested variable) 177 | * Example: variable name 'userfile.name' will return value at $_FILES['userfile']['name'] 178 | * @param mixed $defaultValue the default value to be returned when the $_FILES variable does not exist 179 | * @return mixed 180 | * @since 1.2.1 181 | */ 182 | public static function FILES($name, $defaultValue = null) 183 | { 184 | return self::getValueByComplexKeyFromArray($name, $_FILES, $defaultValue); 185 | } 186 | 187 | /** 188 | * Returns the PDO instance 189 | * 190 | * @param string $dbId ID of the DB component, default value is 'db' 191 | * @return \PDO the PDO instance, null if the connection is not established yet 192 | * @since 1.1.3 193 | */ 194 | public static function getPdo($dbId = 'db') 195 | { 196 | return Yii::app()->getComponent($dbId)->getPdoInstance(); 197 | } 198 | 199 | /** 200 | * Returns the relative URL for the application 201 | * 202 | * @param bool $absolute whether to return an absolute URL. Defaults to false, meaning returning a relative one (@since 1.1.0) 203 | * @return string 204 | */ 205 | public static function baseUrl($absolute = false) 206 | { 207 | return Yii::app()->getComponent('request')->getBaseUrl($absolute); 208 | } 209 | 210 | /** 211 | * Return if the request is sent via secure channel (https) 212 | * 213 | * @return bool 214 | * @since 1.1.0 215 | */ 216 | public static function isSecureConnection() 217 | { 218 | return Yii::app()->getComponent('request')->getIsSecureConnection(); 219 | } 220 | 221 | /** 222 | * Returns whether this is an AJAX (XMLHttpRequest) request 223 | * 224 | * @return bool 225 | * @since 1.1.0 226 | */ 227 | public static function isAjaxRequest() 228 | { 229 | return Yii::app()->getComponent('request')->getIsAjaxRequest(); 230 | } 231 | 232 | /** 233 | * Returns whether this is a PUT request 234 | * 235 | * @return bool 236 | * @since 1.1.0 237 | */ 238 | public static function isPutRequest() 239 | { 240 | return Yii::app()->getComponent('request')->getIsPutRequest(); 241 | } 242 | 243 | /** 244 | * Returns whether this is a DELETE request 245 | * 246 | * @return bool 247 | * @since 1.1.0 248 | */ 249 | public static function isDeleteRequest() 250 | { 251 | return Yii::app()->getComponent('request')->getIsDeleteRequest(); 252 | } 253 | 254 | /** 255 | * Returns whether this is a POST request 256 | * 257 | * @return bool 258 | * @since 1.1.0 259 | */ 260 | public static function isPostRequest() 261 | { 262 | return Yii::app()->getComponent('request')->getIsPostRequest(); 263 | } 264 | 265 | /** 266 | * Deletes a value with the specified key from cache 267 | * 268 | * @param string $key the key of the value to be deleted 269 | * @param string $cacheId ID of the cache component, defaults to 'cache' (@since 1.1.3) 270 | * @return boolean 271 | */ 272 | public static function deleteCache($key, $cacheId = 'cache') 273 | { 274 | return Yii::app()->getComponent($cacheId)->delete($key); 275 | } 276 | 277 | /** 278 | * Retrieves a value from cache with a specified key 279 | * 280 | * @param string $key a key identifying the cached value 281 | * @param string $cacheId ID of the cache component, defaults to 'cache' (@since 1.1.3) 282 | * @return mixed 283 | */ 284 | public static function getCache($key, $cacheId = 'cache') 285 | { 286 | return Yii::app()->getComponent($cacheId)->get($key); 287 | } 288 | 289 | /** 290 | * Stores a value identified by a key into cache. If the cache already contains such a key, 291 | * the existing value and expiration time will be replaced with the new ones. 292 | * 293 | * @param string $key the key identifying the value to be cached 294 | * @param mixed $value the value to be cached 295 | * @param integer $expire the number of seconds in which the cached value will expire, 0 means never expire 296 | * @param ICacheDependency $dependency dependency of the cached item. 297 | * If the dependency changes, the item is labeled invalid (see {@link ICacheDependency}) 298 | * @param string $cacheId ID of the cache component, defaults to 'cache' (@since 1.1.3) 299 | * @return boolean 300 | */ 301 | public static function setCache($key, $value, $expire = 0, $dependency = null, $cacheId = 'cache') 302 | { 303 | return Yii::app()->getComponent($cacheId)->set($key, $value, $expire, $dependency); 304 | } 305 | 306 | /** 307 | * Removes a cookie with the specified name. Since Yii v1.1.11, the second parameter is available 308 | * that can be used to specify the options of the CHttpCookie being removed (see {@link CCookieCollection::remove}) 309 | * 310 | * @param string $name cookie name 311 | * @param array $options cookie configuration array consisting of name-value pairs (@since 1.3.0) 312 | * @return CHttpCookie|null The removed cookie object or null if cookie doesn't exist 313 | */ 314 | public static function deleteCookie($name, $options = array()) 315 | { 316 | return Yii::app()->getComponent('request')->getCookies()->remove($name, $options); 317 | } 318 | 319 | /** 320 | * Returns the cookie with the specified name 321 | * 322 | * @param string $name cookie name 323 | * @param mixed $defaultValue the default value to be returned when the cookie does not exist (@since 1.1.0) 324 | * @return mixed 325 | */ 326 | public static function getCookie($name, $defaultValue = null) 327 | { 328 | $cookie = Yii::app()->getComponent('request')->getCookies()->itemAt($name); 329 | 330 | if ($cookie) { 331 | return $cookie->value; 332 | } 333 | 334 | return $defaultValue; 335 | } 336 | 337 | /** 338 | * Adds a cookie with the specified name 339 | * 340 | * @param string $name cookie name 341 | * @param string|CHttpCookie $value cookie value or CHttpCookie object 342 | * (if it's CHttpCookie object than all following params are ignored, @since 1.3.0) 343 | * @param int $expire the time in seconds after which the cookie expires (84600 means 1 day). 344 | * Defaults to 0, meaning "until the browser is closed". 345 | * @param string $path the path on the server in which the cookie will be available on. The default is '/'. 346 | * @param string $domain domain of the cookie 347 | * @param bool $secure whether cookie should be sent via secure connection (@since 1.3.0) 348 | * @param bool $httpOnly whether the cookie should be accessible only through the HTTP protocol. 349 | * By setting this property to true, the cookie will not be accessible by scripting languages, such as JavaScript, 350 | * which can effectly help to reduce identity theft through XSS attacks. Note, this property is only effective for 351 | * PHP 5.2.0 or above. (@since 1.3.0) 352 | */ 353 | public static function setCookie($name, $value, $expire = null, $path = '/', $domain = '', $secure = false, $httpOnly = false) 354 | { 355 | if ($value instanceof CHttpCookie) { 356 | $cookie = $value; 357 | } else { 358 | $cookie = new CHttpCookie($name, $value); 359 | $cookie->expire = $expire ? ($expire + time()) : 0; 360 | $cookie->path = $path; 361 | $cookie->domain = $domain; 362 | $cookie->secure = $secure; 363 | $cookie->httpOnly = $httpOnly; 364 | } 365 | 366 | Yii::app()->getComponent('request')->getCookies()->add($name, $cookie); 367 | } 368 | 369 | /** 370 | * Returns the random token used to perform CSRF validation 371 | * 372 | * @return string 373 | */ 374 | public static function csrf() 375 | { 376 | return Yii::app()->getComponent('request')->getCsrfToken(); 377 | } 378 | 379 | /** 380 | * Returns the name of the token used to prevent CSRF, defaults to 'YII_CSRF_TOKEN' 381 | * 382 | * @return string 383 | */ 384 | public static function csrfName() 385 | { 386 | return Yii::app()->getComponent('request')->csrfTokenName; 387 | } 388 | 389 | /** 390 | * Returns ready to use 'key: value' string with CSRF token 391 | * Primary usage: AJAX POST requests 392 | * 393 | * jQuery example: 394 | * $.post('url', { param: "blabla", =Y::csrfJsParam();?> }, ...) 395 | * becomes: 396 | * $.post('url', { param: "blabla", "YII_CSRF_TOKEN": "n32Nm3112nqBQIjf..." }, ...) 397 | * 398 | * @return string 399 | */ 400 | public static function csrfJsParam() 401 | { 402 | $request = Yii::app()->getComponent('request'); 403 | 404 | return '"' . $request->csrfTokenName . '":"' . $request->getCsrfToken() . '"'; 405 | } 406 | 407 | /** 408 | * Shortcut with 'pre' tags for dump function of CVarDumper class 409 | * 410 | * @param mixed $var variable to be dumped 411 | * @param boolean $doEnd whether the application should be stopped after dumping 412 | */ 413 | public static function dump($var, $doEnd = true) 414 | { 415 | echo ''; 416 | CVarDumper::dump($var, 10, true); 417 | echo ''; 418 | 419 | if ($doEnd) { 420 | Yii::app()->end(); 421 | } 422 | } 423 | 424 | /** 425 | * Prints some text and stops the application 426 | * 427 | * @param string $text text to be printed before application stopped 428 | */ 429 | public static function end($text = '') 430 | { 431 | echo $text; 432 | Yii::app()->end(); 433 | } 434 | 435 | /** 436 | * Converts data to JSON/JSONP, prints it out and stops the application 437 | * 438 | * @param mixed $data data to be converted in JSON 439 | * @param int $options JSON options (JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, 440 | * JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT) (@since 1.1.3) 441 | * Note, this parameter is only effective when json_encode function is available! 442 | * @param string $callback name of the callback function for JSONP response 443 | */ 444 | public static function endJson($data, $options = 0, $callback = '') 445 | { 446 | $result = function_exists('json_encode') ? json_encode($data, $options) : CJSON::encode($data); 447 | 448 | if (empty($callback)) { 449 | header('Content-Type: application/json;'); 450 | echo $result; 451 | } else { 452 | header('Content-Type: application/javascript;'); 453 | echo $callback . '(' . $result . ');'; 454 | } 455 | 456 | Yii::app()->end(); 457 | } 458 | 459 | /** 460 | * Returns/stores a flash message. A flash message is available only in the current and the next requests. 461 | * 462 | * @param string $key key identifying the flash message 463 | * @param mixed $message flash message to store or false to get a flash message (null to remove flash message) 464 | * Example: 465 | * Y::flash('a', 'b') - stores flash message 'b' 466 | * Y::flash('a') - returns flash message for key 'a' 467 | * Y::flash('a', null) - removes flash message with key 'a' 468 | * @return string 469 | */ 470 | public static function flash($key, $message = false) 471 | { 472 | $user = Yii::app()->getComponent('user'); 473 | 474 | if ($message === false) { 475 | return $user->getFlash($key); 476 | } else { 477 | $user->setFlash($key, $message); 478 | } 479 | } 480 | 481 | /** 482 | * Whether or not user have a flash message with specified key 483 | * 484 | * @param string $key key identifying the flash message 485 | * @return bool 486 | * @since 1.1.2 487 | */ 488 | public static function hasFlash($key) 489 | { 490 | return Yii::app()->getComponent('user')->hasFlash($key); 491 | } 492 | 493 | /** 494 | * Stores a flash message and redirects to specified route 495 | * 496 | * @param string $key key identifying the flash message 497 | * @param string $message flash message 498 | * @param string $route the URL route to redirect to (see {@link CController::createUrl}) 499 | * @param array $params additional GET parameters (see {@link CController::createUrl}) 500 | */ 501 | public static function flashAndRedirect($key, $message, $route, $params = array()) 502 | { 503 | Yii::app()->getComponent('user')->setFlash($key, $message); 504 | Yii::app()->getComponent('request')->redirect(self::url($route, $params)); 505 | } 506 | 507 | /** 508 | * Performs access check for this user 509 | * 510 | * @param string $operation the name of the operation that need access check 511 | * @param array $params name-value pairs that would be passed to business rules associated with the tasks and roles 512 | * assigned to the user. Since Yii v1.1.11 a param with name 'userId' is added to this array, which holds 513 | * the value of getId() when CDbAuthManager or CPhpAuthManager is used (@since 1.3.0) 514 | * @param bool $allowCaching whether to allow caching the result of access check. 515 | * When this parameter is true (default), if the access check of an operation was performed before, 516 | * its result will be directly returned when calling this method to check the same operation. If this parameter is 517 | * false, this method will always call CAuthManager::checkAccess to obtain the up-to-date access result. Note that 518 | * this caching is effective only within the same request and only works when $params=array() (@since 1.3.0) 519 | * @return boolean whether the operations can be performed by this user 520 | * @since 1.0.2 521 | */ 522 | public static function checkAccess($operation, $params = array(), $allowCaching = true) 523 | { 524 | return Yii::app()->getComponent('user')->checkAccess($operation, $params, $allowCaching); 525 | } 526 | 527 | /** 528 | * Returns true if the user is authenticated, otherwise - false 529 | * 530 | * @return boolean 531 | */ 532 | public static function isAuthenticated() 533 | { 534 | return !Yii::app()->getComponent('user')->getIsGuest(); 535 | } 536 | 537 | /** 538 | * Returns true if the user is a guest (not authenticated), otherwise - false 539 | * 540 | * @return boolean 541 | */ 542 | public static function isGuest() 543 | { 544 | return Yii::app()->getComponent('user')->getIsGuest(); 545 | } 546 | 547 | /** 548 | * Returns user-defined application parameter 549 | * 550 | * @param string $key key identifying the parameter (could be used dot delimiter for nested key) 551 | * Example: 'Media.Foto.thumbsize' will return value at ['Media']['Foto']['thumbsize'] 552 | * @param mixed $defaultValue the default value to be returned when the parameter variable does not exist 553 | * @return mixed 554 | */ 555 | public static function param($key, $defaultValue = null) 556 | { 557 | return self::getValueByComplexKeyFromArray($key, Yii::app()->getParams(), $defaultValue); 558 | } 559 | 560 | /** 561 | * Redirects the browser to the specified route 562 | * 563 | * @param string $route the URL route to redirect to (see {@link CController::createUrl}) 564 | * @param array $params additional GET parameters (see {@link CController::createUrl}) 565 | */ 566 | public static function redirect($route, $params = array()) 567 | { 568 | Yii::app()->getComponent('request')->redirect(self::url($route, $params)); 569 | } 570 | 571 | /** 572 | * Redirects the browser to the specified route if the user is authenticated 573 | * 574 | * @param string $route the URL route to redirect to (see {@link CController::createUrl}) 575 | * @param array $params additional GET parameters (see {@link CController::createUrl}) 576 | */ 577 | public static function redirectIfAuthenticated($route, $params = array()) 578 | { 579 | if (!Yii::app()->getComponent('user')->getIsGuest()) { 580 | Yii::app()->getComponent('request')->redirect(self::url($route, $params)); 581 | } 582 | } 583 | 584 | /** 585 | * Redirects the browser to the specified route if the user is a guest 586 | * 587 | * @param string $route the URL route to redirect to (see {@link CController::createUrl}) 588 | * @param array $params additional GET parameters (see {@link CController::createUrl}) 589 | */ 590 | public static function redirectIfGuest($route, $params = array()) 591 | { 592 | if (Yii::app()->getComponent('user')->getIsGuest()) { 593 | Yii::app()->getComponent('request')->redirect(self::url($route, $params)); 594 | } 595 | } 596 | 597 | /** 598 | * Prints application memory, SQL queries and time usage 599 | * 600 | * @param boolean $return whether data should be returned or printed out 601 | * @return string|null 602 | */ 603 | public static function stats($return = false) 604 | { 605 | $stats = ''; 606 | $dbStats = Yii::app()->getDb()->getStats(); 607 | 608 | if (is_array($dbStats)) { 609 | $stats = 'SQL queries: ' . $dbStats[0] . ' (in ' . round($dbStats[1], 5) . ' seconds)
'; 610 | } 611 | 612 | $logger = Yii::getLogger(); 613 | $memory = round($logger->getMemoryUsage() / 1048576, 3); 614 | $time = round($logger->getExecutionTime(), 3); 615 | 616 | $stats .= 'Used memory: ' . $memory . ' Mb
'; 617 | $stats .= 'Execution time: ' . $time . ' seconds'; 618 | 619 | if ($return) { 620 | return $stats; 621 | } 622 | 623 | echo $stats; 624 | } 625 | 626 | /** 627 | * Returns a relative URL based on the given controller and action information 628 | * For more information see {@link CApplication::createUrl} and {@link CController::createUrl} 629 | * 630 | * @param string $route the URL route, this should be in the format of 'ControllerID/ActionID' 631 | * @param array $params additional GET parameters (name=>value), both the name and value will be URL-encoded 632 | * @return string 633 | */ 634 | public static function url($route, $params = array()) 635 | { 636 | if (is_object($controller = Yii::app()->getController())) { 637 | return $controller->createUrl($route, $params); 638 | } 639 | 640 | return Yii::app()->createUrl($route, $params); 641 | } 642 | 643 | /** 644 | * Returns a value that uniquely represents the user, if null - it means the user is a guest 645 | * 646 | * @return mixed 647 | */ 648 | public static function userId() 649 | { 650 | return Yii::app()->getComponent('user')->getId(); 651 | } 652 | 653 | /** 654 | * Returns the array variable value or $defaultValue if the array variable does not exist 655 | * 656 | * @param string $key the array variable name (could be used dot delimiter for nested variable) 657 | * Example: variable name 'Media.Foto.thumbsize' will return value at $array['Media']['Foto']['thumbsize'] 658 | * @param array $array an array containing variable to return 659 | * @param mixed $defaultValue the default value to be returned when the array variable does not exist 660 | * @return mixed 661 | */ 662 | public static function getValueByComplexKeyFromArray($key, $array, $defaultValue = null) 663 | { 664 | if (strpos($key, '.') === false) { 665 | return (isset($array[$key])) ? $array[$key] : $defaultValue; 666 | } 667 | 668 | $keys = explode('.', $key); 669 | $firstKey = array_shift($keys); 670 | 671 | if (!isset($array[$firstKey])) { 672 | return $defaultValue; 673 | } 674 | 675 | $value = $array[$firstKey]; 676 | 677 | foreach ($keys as $k) { 678 | if (!isset($value[$k]) && !array_key_exists($k, $value)) { 679 | return $defaultValue; 680 | } 681 | $value = $value[$k]; 682 | } 683 | 684 | return $value; 685 | } 686 | } 687 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "svyatov/yii-shortcut", 3 | "type": "library", 4 | "description": "Shortcuts for Yii framework", 5 | "keywords": ["yii","shortcut","util","helper"], 6 | "homepage": "https://github.com/svyatov/Yii-shortcut", 7 | "license": "BSD-3-Clause", 8 | "authors": [ 9 | { 10 | "name": "Leonid Svyatov", 11 | "email": "leonid@svyatov.ru", 12 | "homepage": "http://svyatov.ru", 13 | "role": "Developer" 14 | } 15 | ], 16 | "support": { 17 | "email": "leonid@svyatov.ru", 18 | "issues": "https://github.com/svyatov/Yii-shortcut/issues", 19 | "source": "https://github.com/svyatov/Yii-shortcut" 20 | }, 21 | "require": { 22 | "php": ">=5.3.2" 23 | }, 24 | "autoload": { 25 | "classmap": ["Y.php"] 26 | } 27 | } 28 | --------------------------------------------------------------------------------