| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Imagify\Dependencies\League\Container\Inflector; |
| 6 |
|
| 7 |
use Imagify\Dependencies\League\Container\Argument\ArgumentResolverInterface; |
| 8 |
use Imagify\Dependencies\League\Container\Argument\ArgumentResolverTrait; |
| 9 |
use Imagify\Dependencies\League\Container\ContainerAwareTrait; |
| 10 |
|
| 11 |
class Inflector implements ArgumentResolverInterface, InflectorInterface |
| 12 |
{ |
| 13 |
use ArgumentResolverTrait; |
| 14 |
use ContainerAwareTrait; |
| 15 |
|
| 16 |
/** |
| 17 |
* @var string |
| 18 |
*/ |
| 19 |
protected $type; |
| 20 |
|
| 21 |
/** |
| 22 |
* @var callable|null |
| 23 |
*/ |
| 24 |
protected $callback; |
| 25 |
|
| 26 |
/** |
| 27 |
* @var array |
| 28 |
*/ |
| 29 |
protected $methods = []; |
| 30 |
|
| 31 |
/** |
| 32 |
* @var array |
| 33 |
*/ |
| 34 |
protected $properties = []; |
| 35 |
|
| 36 |
public function __construct(string $type, ?callable $callback = null) |
| 37 |
{ |
| 38 |
$this->type = $type; |
| 39 |
$this->callback = $callback; |
| 40 |
} |
| 41 |
|
| 42 |
public function getType(): string |
| 43 |
{ |
| 44 |
return $this->type; |
| 45 |
} |
| 46 |
|
| 47 |
public function invokeMethod(string $name, array $args): InflectorInterface |
| 48 |
{ |
| 49 |
$this->methods[$name] = $args; |
| 50 |
return $this; |
| 51 |
} |
| 52 |
|
| 53 |
public function invokeMethods(array $methods): InflectorInterface |
| 54 |
{ |
| 55 |
foreach ($methods as $name => $args) { |
| 56 |
$this->invokeMethod($name, $args); |
| 57 |
} |
| 58 |
|
| 59 |
return $this; |
| 60 |
} |
| 61 |
|
| 62 |
public function setProperty(string $property, $value): InflectorInterface |
| 63 |
{ |
| 64 |
$this->properties[$property] = $this->resolveArguments([$value])[0]; |
| 65 |
return $this; |
| 66 |
} |
| 67 |
|
| 68 |
public function setProperties(array $properties): InflectorInterface |
| 69 |
{ |
| 70 |
foreach ($properties as $property => $value) { |
| 71 |
$this->setProperty($property, $value); |
| 72 |
} |
| 73 |
|
| 74 |
return $this; |
| 75 |
} |
| 76 |
|
| 77 |
public function inflect(object $object): void |
| 78 |
{ |
| 79 |
$properties = $this->resolveArguments(array_values($this->properties)); |
| 80 |
$properties = array_combine(array_keys($this->properties), $properties); |
| 81 |
|
| 82 |
// array_combine() can technically return false |
| 83 |
foreach ($properties ?: [] as $property => $value) { |
| 84 |
$object->{$property} = $value; |
| 85 |
} |
| 86 |
|
| 87 |
foreach ($this->methods as $method => $args) { |
| 88 |
$args = $this->resolveArguments($args); |
| 89 |
$callable = [$object, $method]; |
| 90 |
call_user_func_array($callable, $args); |
| 91 |
} |
| 92 |
|
| 93 |
if ($this->callback !== null) { |
| 94 |
call_user_func($this->callback, $object); |
| 95 |
} |
| 96 |
} |
| 97 |
} |
| 98 |
|