forked from stefna/php-code-builder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonSerializeMethod.php
More file actions
51 lines (45 loc) · 1.67 KB
/
JsonSerializeMethod.php
File metadata and controls
51 lines (45 loc) · 1.67 KB
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
42
43
44
45
46
47
48
49
50
51
<?php declare(strict_types=1);
namespace Stefna\PhpCodeBuilder\CodeHelper\Methods;
use Stefna\PhpCodeBuilder\CodeHelper\ArrayCode;
use Stefna\PhpCodeBuilder\CodeHelper\CodeInterface;
use Stefna\PhpCodeBuilder\CodeHelper\JsonSerializeTypeCallResolver;
use Stefna\PhpCodeBuilder\CodeHelper\ReturnCode;
use Stefna\PhpCodeBuilder\CodeHelper\TypeCallResolverInterface;
use Stefna\PhpCodeBuilder\FlattenSource;
use Stefna\PhpCodeBuilder\PhpClass;
use Stefna\PhpCodeBuilder\PhpMethod;
use Stefna\PhpCodeBuilder\PhpVariable;
use Stefna\PhpCodeBuilder\Renderer\RenderInterface;
/**
* @phpstan-import-type SourceArray from RenderInterface
*/
final class JsonSerializeMethod extends PhpMethod
{
public static function fromClass(PhpClass $class, ?TypeCallResolverInterface $resolver = null): self
{
$resolver = $resolver ?? new JsonSerializeTypeCallResolver();
$source = [];
$array = [];
foreach ($class->getVariables() as $identifier) {
/** @var PhpVariable $variable */
$variable = $class->getVariable($identifier);
$typeCall = $resolver->resolve($variable->getType(), $variable->getCodeReference());
$array[$variable->getIdentifier()->toString()] = $typeCall->getCall();
if ($typeCall->getExtraSource()) {
$source = FlattenSource::applySourceOn($typeCall->getExtraSource(), $source);
}
}
$source[] = new ReturnCode(new ArrayCode($array));
return self::fromSource($source);
}
/**
* @phpstan-param SourceArray|CodeInterface $source
*/
public static function fromSource(array|CodeInterface $source): self
{
if ($source instanceof CodeInterface) {
$source = $source->getSourceArray();
}
return new self(self::PUBLIC_ACCESS, 'jsonSerialize', [], $source);
}
}