Skip to content
Permalink
Browse files

Added preg::grep_keys() #48

  • Loading branch information...
Danon committed Aug 25, 2019
1 parent f0d1565 commit 2f8664eace5e0a324e075b186e806dcf36ed2692
Showing with 83 additions and 1 deletion.
  1. +2 −1 ChangeLog.md
  2. +5 −0 src/TRegx/SafeRegex/preg.php
  3. +76 −0 test/Functional/TRegx/SafeRegex/pregGrepKeysTest.php
@@ -8,7 +8,8 @@ Incoming in 0.9.2
* Added `Match.group().replace()` 🔥
* Added `pattern()->match()->unique()`
* Added `Pattern::inject()`/`Pattern::bind()`

* SafeRegex
* Added `preg::grep_keys()`, that works exactly like `preg::grep()`, but filters by keys (also accepts [`PREG_GREP_INVERT`](https://www.php.net/manual/en/function.preg-grep.php))
* Enhancements/updates
* Method `by()->group()->orElse()` now receives lazy-loaded `Match`, instead of a subject
* Added `withReferences()` to `CompositePattern.chainedReplace()`
@@ -446,6 +446,11 @@ public static function grep($pattern, array $input, $flags = 0): array
}, new SilencedSuspectedReturnStrategy());
}
public static function grep_keys($pattern, array $input, $flags = 0): array
{
return \array_intersect_key($input, \array_flip(self::grep($pattern, \array_keys($input), $flags)));
}
/**
* Quote regular expression characters
* @link https://php.net/manual/en/function.preg-quote.php
@@ -0,0 +1,76 @@
<?php
namespace Test\Functional\TRegx\SafeRegex;
use PHPUnit\Framework\TestCase;
use TRegx\CleanRegex\Exception\CleanRegex\MalformedPatternException;
use TRegx\SafeRegex\Exception\CompileSafeRegexException;
use TRegx\SafeRegex\preg;
class pregGrepKeysTest extends TestCase
{
/**
* @test
*/
public function shouldGrepKeys()
{
// given
$input = [
'9' => ['Foo', 'Bar'],
'a' => false,
'10' => true,
'b' => new \stdClass(),
'11' => true,
];
// when
$result = preg::grep_keys('/\d+/', $input);
// then
$this->assertEquals(['9' => ['Foo', 'Bar'], '10' => true, '11' => true], $result);
}
/**
* @test
*/
public function shouldGrepKeys_inverted()
{
// given
$input = [
'9' => ['Foo', 'Bar'],
'a' => false,
'10' => true,
'b' => new \stdClass(),
'11' => true
];
// when
$result = preg::grep_keys('/\d+/', $input, PREG_GREP_INVERT);
// then
$this->assertEquals(['a' => false, 'b' => new \stdClass()], $result);
}
/**
* @test
*/
public function shouldGetEmptyArray_emptyInput_preg_grep_keys()
{
// when
$result = preg::grep_keys('//', []);
// then
$this->assertEquals([], $result);
}
/**
* @test
*/
public function shouldThrow_forInvalidPattern()
{
// then
$this->expectException(MalformedPatternException::class);
// when
preg::grep_keys('/+/', []);
}
}

0 comments on commit 2f8664e

Please sign in to comment.
You can’t perform that action at this time.