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

Section:
Sub-section::
Languages:


samdark
  • Reputation: 349
  • Snippets: 57
  • Revisions: 5

Thanks to closures we can avoid using global flag which spoils the scope.

The code could be executed in any browser console. To trigger it, click anywhere on the page.

window.addEventListener('click', function () {
    var i = 0;
    return function () {
        window.alert('You\'ve clicked it ' + (++i) + ' time(s).');
    };
}());
IStranger
  • Reputation: 17
  • Snippets: 8
  • Revisions: 0

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"
IStranger
  • Reputation: 17
  • Snippets: 8
  • Revisions: 0

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));
}
samdark
  • Reputation: 349
  • Snippets: 57
  • Revisions: 5

A short and reliable way to detect if the script is run in Windows environment.

if (DIRECTORY_SEPARATOR === '\\') {
    // ...
}
SilverFire
  • Reputation: 3
  • Snippets: 1
  • Revisions: 0

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;
}
samdark
  • Reputation: 349
  • Snippets: 57
  • Revisions: 5

It's possible to shuffle array once a week without storing anything. I've found the solution at StackOverflow.

It's based on initializing random number generator which is used by shuffle() with a seed that's constant for each week. date('W') is a week number in a year which fits the purpose well. After shuffling is done RNG is put back to normal by calling srand() with no argument i.e. initilizing it with random seed.

srand(date('W'));
shuffle($array);
srand();
samdark
  • Reputation: 349
  • Snippets: 57
  • Revisions: 5

Sometimes you don't want to spoil API in order to test private or protected method of a class.

A good example is a public method that calls one of two private methods depending on the presence of PECL extension. Running tests twice with different PHP configuration is a waste of time. Making methods public isn't good for API.

function callPrivateMethod($object, $method, $args)
{
    $classReflection = new \ReflectionClass(get_class($object));
    $methodReflection = $classReflection->getMethod($method);
    $methodReflection->setAccessible(true);
    $result = $methodReflection->invokeArgs($object, $args);
    $methodReflection->setAccessible(false);
    return $result;
}

$myObject = new MyClass();
callPrivateMethod($myObject, 'hello', ['world']);
Snippet,  PHP

Creating a tree

dfatt
  • Reputation: 260
  • Snippets: 53
  • Revisions: 7

I've been searching for a good way to form a tree. I think this one is ideal. Can you make it better?

private function buildTree($data)
{
	$tree       = [];
	$references = [];

	foreach ($data as $id => &$node) {
		$references[$node['id']] = &$node;
		$node['children'] = [];

		if (is_null($node['parent_id'])) {
			$tree[] = &$node;
		} else {
			$references[$node['parent_id']]['children'][] = &$node;
		}
	}

	return $tree;
}
samdark
  • Reputation: 349
  • Snippets: 57
  • Revisions: 5

Very useful in case when foreign constraints aren't working.

SELECT TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA='my_db_name'
AND TABLE_TYPE='BASE TABLE'
AND ENGINE IN ('MARIA','MyISAM')
Snippet,  PHP

PHP4 constructor

samdark
  • Reputation: 349
  • Snippets: 57
  • Revisions: 5

Legacy PHP4 behavior is still there in current PHP versions. Could lead to debug nightmare.

class Test
{
	public function test()
	{
		echo 'Hello!';
		// it could be less innocent i.e. format disk ;)
	}
}

$test = new Test();

// runs Test::test()