ILIAS  trunk Revision v11.0_alpha-3011-gc6b235a2e85
AddLabels.php
Go to the documentation of this file.
1<?php
2
19declare(strict_types=1);
20
22
27use InvalidArgumentException;
28
32class AddLabels implements Transformation
33{
35
37 private array $labels;
39
44 public function __construct(array $labels, Factory $factory)
45 {
46 $this->labels = $labels;
47 $this->factory = $factory;
48 }
49
54 public function transform($from): array
55 {
56 if (!is_array($from)) {
57 throw new InvalidArgumentException(__METHOD__ . " argument is not an array.");
58 }
59
60 if (count($from) !== count($this->labels)) {
61 throw new InvalidArgumentException(__METHOD__ . " number of items in arrays are not equal.");
62 }
63
64 return array_combine($this->labels, $from);
65 }
66
70 public function applyTo(Result $result): Result
71 {
72 $dataValue = $result->value();
73 if (false === is_array($dataValue)) {
74 $exception = new InvalidArgumentException(__METHOD__ . " argument is not an array.");
75 return $this->factory->error($exception);
76 }
77
78 if (count($dataValue) !== count($this->labels)) {
79 $exception = new InvalidArgumentException(__METHOD__ . " number of items in arrays are not equal.");
80 return $this->factory->error($exception);
81 }
82
83 $value = array_combine($this->labels, $dataValue);
84 $result = $this->factory->ok($value);
85
86 return $result;
87 }
88}
factory()
Builds data types.
Definition: Factory.php:36
Adds to any array keys for each value.
Definition: AddLabels.php:33
applyTo(Result $result)
@inheritDoc
Definition: AddLabels.php:70
__construct(array $labels, Factory $factory)
Definition: AddLabels.php:44
A result encapsulates a value or an error and simplifies the handling of those.
Definition: Result.php:29
value()
Get the encapsulated value.
A transformation is a function from one datatype to another.