ILIAS  release_6 Revision v6.24-5-g0c8bfefb3b8
AddLabels.php
Go to the documentation of this file.
1<?php
2/* Copyright (c) 2017 Stefan Hecken <stefan.hecken@concepts-and-training.de> Extended GPL, see docs/LICENSE */
3
5
9
13class AddLabels implements Transformation
14{
18 protected $labels;
19
23 private $factory;
24
29 public function __construct(array $labels, Factory $factory)
30 {
31 $this->labels = $labels;
32 $this->factory = $factory;
33 }
34
38 public function transform($from)
39 {
40 if (!is_array($from)) {
41 throw new \InvalidArgumentException(__METHOD__ . " argument is not an array.");
42 }
43
44 if (count($from) != count($this->labels)) {
45 throw new \InvalidArgumentException(__METHOD__ . " number of items in arrays are not equal.");
46 }
47
48 return array_combine($this->labels, $from);
49 }
50
54 public function __invoke($from)
55 {
56 return $this->transform($from);
57 }
58
62 public function applyTo(Result $data) : Result
63 {
64 $dataValue = $data->value();
65 if (false === is_array($dataValue)) {
66 $exception = new \InvalidArgumentException(__METHOD__ . " argument is not an array.");
67 return $this->factory->error($exception);
68 }
69
70 if (count($dataValue) != count($this->labels)) {
71 $exception = new \InvalidArgumentException(__METHOD__ . " number of items in arrays are not equal.");
72 return $this->factory->error($exception);
73 }
74
75 $value = array_combine($this->labels, $dataValue);
76 $result = $this->factory->ok($value);
77
78 return $result;
79 }
80}
$result
An exception for terminatinating execution or to throw for unit testing.
Builds data types.
Definition: Factory.php:20
Adds to any array keys for each value.
Definition: AddLabels.php:14
applyTo(Result $data)
Perform the transformation and reify possible failures.If $data->isError(), the method MUST do nothin...
Definition: AddLabels.php:62
__invoke($from)
Transformations should be callable.This MUST do the same as transform.InvalidArgumentException if the...
Definition: AddLabels.php:54
transform($from)
Perform the transformation.Please use this for transformations. It's more performant than calling inv...
Definition: AddLabels.php:38
__construct(array $labels, Factory $factory)
Definition: AddLabels.php:29
A result encapsulates a value or an error and simplifies the handling of those.
Definition: Result.php:12
A transformation is a function from one datatype to another.
$data
Definition: storeScorm.php:23