Skip to content

Commit 0c31ab8

Browse files
author
Greg Bowler
committed
feature: implement selectPrefix
closes #13
1 parent e951e77 commit 0c31ab8

File tree

3 files changed

+59
-1
lines changed

3 files changed

+59
-1
lines changed

src/Input.php

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
use ArrayAccess;
55
use Countable;
6+
use Gt\Input\Trigger\NeverTrigger;
67
use Gt\Json\JsonDecodeException;
78
use Gt\Json\JsonObject;
89
use Gt\Json\JsonObjectBuilder;
@@ -243,14 +244,31 @@ public function select(string...$keys):Trigger {
243244
}
244245
}
245246

246-
return $this->newTrigger("with", ...$keys);
247+
return $this->newTrigger("select", ...$keys);
247248
}
248249

249250
/** @deprecated Use select() instead to avoid ambiguity with immutable `with` functions */
250251
public function with(string...$keys):Trigger {
251252
return $this->select(...$keys);
252253
}
253254

255+
public function selectPrefix(string $prefix):Trigger {
256+
$keys = [];
257+
258+
foreach($this->parameters as $key => $param) {
259+
if(str_starts_with($key, $prefix)) {
260+
array_push($keys, $key);
261+
}
262+
}
263+
264+
if($keys) {
265+
return $this->when(...$keys);
266+
}
267+
else {
268+
return new NeverTrigger($this);
269+
}
270+
}
271+
254272
/**
255273
* Return a Trigger that will pass all keys apart from the provided
256274
* keys to its callback.

src/Trigger/NeverTrigger.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?php
2+
namespace Gt\Input\Trigger;
3+
4+
class NeverTrigger extends Trigger {
5+
public function call(callable $callback, string ...$args):Trigger {
6+
return $this;
7+
}
8+
9+
public function orCall(callable $callback, string ...$args):Trigger {
10+
return $this;
11+
}
12+
13+
public function fire():bool {
14+
return false;
15+
}
16+
}

test/phpunit/InputTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -710,6 +710,30 @@ public function testGetBodyJson_withQueryString():void {
710710
self::assertSame(123, $sut->getInt("id"));
711711
}
712712

713+
public function testSelectPrefix_noMatch():void {
714+
$sut = new Input(["id" => 123]);
715+
$trigger = $sut->selectPrefix("io_");
716+
717+
$triggered = false;
718+
$trigger->call(function(...$args)use(&$triggered) {
719+
$triggered = true;
720+
});
721+
$trigger->fire();
722+
self::assertFalse($triggered);
723+
}
724+
725+
public function testSelectPrefix_match():void {
726+
$sut = new Input(["id" => 123, "io_database" => "connect"]);
727+
$trigger = $sut->selectPrefix("io_");
728+
729+
$triggered = false;
730+
$trigger->call(function(...$args)use(&$triggered) {
731+
$triggered = true;
732+
});
733+
$trigger->fire();
734+
self::assertTrue($triggered);
735+
}
736+
713737
public static function dataRandomGetPost():array {
714738
$data = [];
715739

0 commit comments

Comments
 (0)