Для получения полного доступа
зарегистрируйтесь


The function above checks, whether the current controller's action is the same as defined in the defaultRoute property of application.

function isHomePage() {
  $actualRoute = Yii::$app->controller->getRoute();

  list($controller, $actionId) = Yii::$app->createController('');
  $actionId = !empty($actionId) ? $actionId : $controller->defaultAction;
  $defaultRoute = $controller->getUniqueId() . '/' . $actionId;

  return $actualRoute === $defaultRoute;
}

Впринципе ничего особенного, просто сетка на 12 колонок, привязанная к data параметрам

[data-rbk-container] { width: 1170px; margin: 0 auto; }
[data-rbk-row] { display: block; }
[data-rbk-row]:after, [data-rbk-row]:before { content: ' '; display: block; clear: both; height: 0; }
[data-rbk-col] { display: block; box-sizing: border-box; width: 50%; padding: 15px; float: left; }
[data-rbk-col="1"] { width: 8.333%; }
[data-rbk-col="2"] { width: 16.666%;}
[data-rbk-col="10"] { width: 83.333%;}
[data-rbk-col="3"] { width: 25%; }
[data-rbk-col="2.5"] { width: 20%; } /* for 5th colons */
[data-rbk-col="9"] { width: 75%; }
[data-rbk-col="4"] { width: 33.333%; }
[data-rbk-col="8"] { width: 66.666%; }
[data-rbk-col="5"] { width: 41.666%; }
[data-rbk-col="7"] { width: 58.333%; }
[data-rbk-col="11"] { width: 91.666%; }
[data-rbk-col="12"] { width: 100%; }

View Demo

/**
 * Split the SQL dump code and return as queries array.
 * @param string $raw SQL code to parse
 * @return array List of queries
 */
function splitSqlText ( $raw ) {
	// the regex needs a trailing semicolon
	$raw = trim ( (string) $raw );

	if ( substr ( $raw, -1 ) !== ";") {
		$raw .= ";";
	}

	// i spent 3 days figuring out this line
	preg_match_all( "/(?>[^;']|(''|(?>'([^']|\\')*[^\\\]')".
		"))+;/ixU", $raw, $matches, PREG_SET_ORDER );

	$querySplit = [];

	foreach ( $matches as $match ) {
		// get rid of the trailing semicolon
		$querySplit[] = substr( $match[0], 0, -1 );
	}

	return $querySplit;
}
/**
 * Validate MySQL Timestamp
 * @param string $value Value to check (Y-m-d h:i:s)
 * @return bool TRUE on valid | FALSE anyway
 */
function isTimestampValid ( $value ) {
	$date = array();
	if ( !preg_match ('/^(?<y>19\d\d|20\d\d)\-(?<m>0[1-9]|1[0-2])\-' .
		'(?<d>0\d|[1-2]\d|3[0-1]) (?<h>0\d|1\d|2[0-3]' .
		')\:(?<i>[0-5][0-9])\:(?<s>[0-5][0-9])$/', $value, $date) ) {
		return false;
	}

	return checkdate ( $date['m'], $date['d'], $date['y'] );
}

/************
 * EXAMPLE
 ***********/
var_dump ( isTimestampValid ('2016-09-10 23:21:09') );

/***********
 * OUTPUT
 **********/
# (bool) true
/**
 * Generate mime types list using apache svn defination
 * @link http://php.net/manual/en/function.mime-content-type.php#107798
 * @return array [key=>value] pairs of mime types (extension=>mime_type)
 */
function generateMimeTypes () {
	$list = [];
	$url = 'http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types';
    
	foreach ( @explode ( "\n", @file_get_contents ($url) ) as $x ) {
		if ( isset( $x[0] )
			&& $x[0] !== '#'
			&& preg_match_all ( '#([^\s]+)#', $x, $out )
			&& isset( $out[1] )
			&& ( $c = count ( $out[1] ) ) > 1 ) {
			for ( $i = 1; $i < $c; $i++ ) {
				$key = (string) $out[1][$i];
				$list[$key] = $out[1][0];
			}
		}
	}

	return @ksort($list, \SORT_STRING )
		? $list
		: [];
}

/************
 * EXAMPLE
 ***********/
print_r ( generateMimeTypes () );

/***********
 * OUTPUT
 **********/
 [
    '3dml' => 'text/vnd.in3d.3dml'
    '3ds' => 'image/x-3ds'
    '3g2' => 'video/3gpp2'
    '3gp' => 'video/3gpp'
    '7z' => 'application/x-7z-compressed'
    'aab' => 'application/x-authorware-bin'
    'aac' => 'audio/x-aac'
    'aam' => 'application/x-authorware-map'
    'aas' => 'application/x-authorware-seg'
    'abw' => 'application/x-abiword'
    'ac' => 'application/pkix-attr-cert'
    'acc' => 'application/vnd.americandynamics.acc'
    'ace' => 'application/x-ace-compressed'
    'acu' => 'application/vnd.acucobol'
    'acutc' => 'application/vnd.acucorp'
    'adp' => 'audio/adpcm'
    'aep' => 'application/vnd.audiograph'
    'afm' => 'application/x-font-type1'
    'afp' => 'application/vnd.ibm.modcap'
    'ahead' => 'application/vnd.ahead.space'
    'ai' => 'application/postscript'
    'aif' => 'audio/x-aiff',
    ...
]
/**
 * Divide an array into a desired number of split lists
 * @link http://www.php.net/manual/en/function.array-chunk.php#75022
 * @param array $list The Array
 * @param int $size Partition Size
 * @return array The partitioned array
 */
function columnsPartition ( array $list, $size ) {
	$listLen = count ( $list );

	if ( !$listLen || $size < 1 ) {
		return [];
	}

	$partLen = floor ( $listLen / $size );
	$partRem = $listLen % $size;
	$partition = [];
	$mark = 0;

	for ( $px = 0; $px < $size; $px++ ) {
		$increment = ( $px < $partRem ) ? $partLen + 1 : $partLen;

		$partition[ $px ] = array_slice ( $list, $mark, $increment );
		$mark += $increment;
	}

	return $partition;
}

/************
 * EXAMPLE
 ***********/
var_dump ( columnsPartition(range('A','I'), 3) );

/***********
 * OUTPUT
 **********/
array (size=3)
  0 => 
    array (size=3)
      0 => string 'A' (length=1)
      1 => string 'B' (length=1)
      2 => string 'C' (length=1)
  1 => 
    array (size=3)
      0 => string 'D' (length=1)
      1 => string 'E' (length=1)
      2 => string 'F' (length=1)
  2 => 
    array (size=3)
      0 => string 'G' (length=1)
      1 => string 'H' (length=1)
      2 => string 'I' (length=1)
/**
 * Strip text longer then given length
 * @param string $text Text to be stripped
 * @param int $length Length of chars to keep
 * @param string $glueChar (optional) Show when length exceeded
 * @return string|null Stripped text | Text was empty
 */
function getCharsByLength ( $text, $length, $glueChar = '...' ) {
	if ( !trim ($text ) ) {
		return null;
	}

	/** @var int $actualLength */
	$actualLength = function_exists('mb_strlen')
		? mb_strlen($text)
		: strlen($text);

	// desired length is same or less, return as it is
	if ( $actualLength <= $length ) {
		return $text;
	}

	return function_exists ( 'mb_substr' )
		? mb_substr ($text, 0, $length, 'utf8' ) . $glueChar
		: substr ($text, 0, $length ) . $glueChar;
}

/************
 * EXAMPLE
 ***********/
getCharsByLength ('Νο εαμ σθμμο vολθτπατ. Εα εστ ομνεσ ιμπερδιετ εφφιcιαντθρ', 10);

/***********
 * OUTPUT
 **********/
# Νο εαμ σθμ...

High-performance function checks whether specified array contains only integer values (or integer-numeric strings):


/**
 * Checks whether all elements of an array are integers (integer value or string with integer value).
 * Note: this is very efficient method can be used for array with 10000+ items.
 *
 * @param int[]|string[] $array One dimensional array to check
 *
 * @return bool
 */ 
function hasOnlyIntEntries(array $array)
{
    return ctype_digit(join('', $array));
}

Often we need remove CSS classes that begin with certain string. For example: has-state-active, has-state-pending, has-state-disabled. Easiest way is to use wildcards: has-state-*.

Following function supports them (requires jQuery):

/**
 * Removes CSS classes of element using wildcards:
 *
 * @example
 * <code><pre>
 *
 *          // create some element
 *      var $element = $('<div id="#some-element"/>')
 *                          .addClass('base-class has-state-active item item-75')
 *                          .appendTo('body');
 *
 *          // remove classes with few prefixes
 *      removeClassWildcard( $element, 'has-state-* item-*');
 *
 *          // display element classes
 *      console.log($element.attr('class'));    // >> "base-class item"
 *
 * </pre></code>
 *
 * @param {jQuery|*}    $element
 * @param {String}      removals        Classes to delete, for example: 'foo-* bar-*'
 * @returns {jQuery|*}                  Passed element
 */
function removeClassWildcard($element, removals) {
    if (removals.indexOf('*') === -1) {
        // Use native jQuery methods if there is no wildcard matching
        $element.removeClass(removals);
        return $element;
    }

    var patt = new RegExp('\\s' +
            removals.replace(/\*/g, '[A-Za-z0-9-_]+').split(' ').join('\\s|\\s') +
            '\\s', 'g');

    $element.each(function (i, it) {
        var cn = ' ' + it.className + ' ';
        while (patt.test(cn)) {
            cn = cn.replace(patt, ' ');
        }
        it.className = $.trim(cn);
    });

    return $element;
}

Example:


  // create some element
var $element = $('<div id="#some-element"/>')
                  .addClass('base-class has-state-active item item-75')
                  .appendTo('body');

  // remove classes with few prefixes
removeClassWildcard( $element, 'has-state-* item-*');

  // display element classes
console.log($element.attr('class'));    // >> "base-class item"

"Golden" rule of frontend optimization often recommends to insert all JS scripts on page end. However usualy we can't remove <script src="//jquery.js"> from page <head>, because page content can contain many onReady-handlers, for example $(function(){ ... }).

This short snippet allows move jquery.js from <head> to end of <body> without changing onReady-handlers.

Snippet:

<head>
	<script>
		// Fallback code for the jQuery inline scripts on pages:
      if (window.jQuery === undefined) {
          window.jQueryReadyHandlers = [];

          window.$ = window.jQuery = function (callback) {
              window.jQueryReadyHandlers.push(callback);
              return window.$;
          };

          window.$.ready = window.$;
      }
  	</script>
    <!-- ...some head items -->
</head>
<body>

	<!-- ...some page content -->
    
    <script> 
    	// some onReady-handlers
      $(function(){
          console.log('First callback');
      });

      jQuery(document).ready(function(){
          console.log('Second callback');
      });
    </script>
    
    <!-- ...some page content -->


	<script src="//js/jquery.min.js"></script>
    <script>
    	jQuery(window).load(function(){
        	if(window.jQueryReadyHandlers) { 
            	$.each(window.jQueryReadyHandlers, function(index,func){  
                	$(func);
                });
            }
        });
    </script>
</body>