/
ToString.php
41 lines (32 loc) · 869 Bytes
/
ToString.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
namespace Centum\Filter\Cast;
use Centum\Interfaces\Filter\FilterInterface;
use InvalidArgumentException;
use JsonException;
class ToString implements FilterInterface
{
/**
* @throws JsonException
* @throws InvalidArgumentException
*/
public function filter(mixed $value): string
{
if (is_object($value)) {
if (method_exists($value, "__toString")) {
return (string) $value;
}
return serialize($value);
}
if (is_array($value)) {
$json = json_encode($value);
if ($json === false) {
throw new JsonException();
}
return $json;
}
if (!is_null($value) && !is_scalar($value)) {
throw new InvalidArgumentException();
}
return (string) $value;
}
}