Skip to content

Commit a54402e

Browse files
feat: add string manipulation functions for startswith and endswith
1 parent 9e396af commit a54402e

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

src/Runtime/StringValue.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ class StringValue extends RuntimeValue
1414
public function __construct(string $value)
1515
{
1616
parent::__construct($value);
17+
1718
$this->builtins = [
1819
"upper" => new FunctionValue(fn() => new StringValue(strtoupper($this->value))),
1920
"lower" => new FunctionValue(fn() => new StringValue(strtolower($this->value))),
@@ -22,6 +23,30 @@ public function __construct(string $value)
2223
"length" => new NumericValue(strlen($this->value)),
2324
"rstrip" => new FunctionValue(fn() => new StringValue(rtrim($this->value))),
2425
"lstrip" => new FunctionValue(fn() => new StringValue(ltrim($this->value))),
26+
"startswith" => new FunctionValue(function ($args) {
27+
if (count($args) === 0) {
28+
throw new \Exception("startswith() requires at least one argument");
29+
}
30+
31+
$prefix = $args[0];
32+
if (!($prefix instanceof StringValue)) {
33+
throw new \Exception("startswith() requires a string argument");
34+
}
35+
36+
return new BooleanValue(str_starts_with($this->value, $prefix->value));
37+
}),
38+
"endswith" => new FunctionValue(function ($args) {
39+
if (count($args) === 0) {
40+
throw new \Exception("endswith() requires at least one argument");
41+
}
42+
43+
$suffix = $args[0];
44+
if (!($suffix instanceof StringValue)) {
45+
throw new \Exception("endswith() requires a string argument");
46+
}
47+
48+
return new BooleanValue(str_ends_with($this->value, $suffix->value));
49+
}),
2550
"split" => new FunctionValue(fn($args) => new ArrayValue(explode($args[0] ?? ' ', $this->value, $args[1] ?? -1))),
2651
];
2752
}

0 commit comments

Comments
 (0)