/** * Slugify a string * * Simplified slugify that only passes in alphanumeric characters, and replaces runs of others with dashes. * Also only allows alphanumeric characters on start and end. * The result is usable as a part of DNS domain name. */ public static function slugify($string, $maxLength = 255, $hashLength = 6) { mb_regex_encoding('UTF-8'); $hash = mb_substr(hash('sha256', $string), 0, (int) $hashLength); $sanitized = static::sanitize($string); $sanitized = static::maxLength($sanitized, (int) $maxLength - ($hashLength ? (int) $hashLength + 1 : 0)); $sanitized = static::trimNonAlnumEnds($sanitized); // Add partial hash in order to prevent empty or duplicate slugs $sanitized = implode('-', _::filter([$sanitized, $hash])); return $sanitized; }
function _filter($list, $iterator = NULL, $context = NULL) { return Underscore::filter($list, $iterator, $context); }
/** * @tags collections */ public function testFilter() { $even = function ($v) { return !($v & 1); }; // the truth test should be optionnal $this->variable(_::filter([1, 0, 2, null, 3, false, 4, "0"]))->isEqualTo([0 => 1, 2 => 2, 4 => 3, 6 => 4]); // it should work with arrays, objects and iterators $this->typeTolerant([1, 2, 3, 4], [1 => 2, 3 => 4], function ($in, $out) use($even) { $this->array(_::filter($in, $even))->isEqualTo($out); }, [0, -1]); // it should preserve associativity and order $this->variable(_::filter(['a' => 1, 9 => 2, null => 3, 0.2 => 4], $even))->isEqualTo([9 => 2, 0.2 => 4]); // it should be possible to specify a context for the thruth test $this->variable(_::filter([1, 2, 3, 4], function ($v) { return $v % $this->mod == 0; }, (object) ['mod' => 2]))->isEqualTo([1 => 2, 3 => 4]); // it should return an empty array if no item passes the truth test $this->array(_::filter([1, 3, 5, 7], $even))->hasSize(0); }