1<?php
2/* Copyright (c) 2017 Stefan Hecken <stefan.hecken@concepts-and-training.de> Extended GPL, see docs/LICENSE */
3
4namespace ILIAS\Data\Result;
5
6use ILIAS\Data\Result;
7
8/**
9 * A result encapsulates a value or an error and simplifies the handling of those.
10 *
11 * @author Stefan Hecken <stefan.hecken@concepts-and-training.de>
12 */
13class Ok implements Result
14{
15
16    /**
17     * @var mixed
18     */
19    protected $value;
20
21    public function __construct($value)
22    {
23        $this->value = $value;
24    }
25
26    /**
27     * @inheritdoc
28     */
29    public function isOK()
30    {
31        return true;
32    }
33
34    /**
35     * @inheritdoc
36     */
37    public function value()
38    {
39        return $this->value;
40    }
41
42    /**
43     * @inheritdoc
44     */
45    public function isError()
46    {
47        return false;
48    }
49
50    /**
51     * @inheritdoc
52     */
53    public function error()
54    {
55        throw new \LogicException("This is a OK result. No error message available");
56    }
57
58    /**
59     * @inheritdoc
60     */
61    public function valueOr($default)
62    {
63        return $this->value;
64    }
65
66    /**
67     * @inheritdoc
68     */
69    public function map(callable $f)
70    {
71        $clone = clone $this;
72        $value = $f($this->value);
73        $clone->value = $value;
74        return $clone;
75    }
76
77    /**
78     * @inheritdoc
79     */
80    public function then(callable $f)
81    {
82        $result = $f($this->value);
83
84        if ($result === null) {
85            return $this;
86        }
87
88        if (!$result instanceof Result) {
89            throw new \UnexpectedValueException("The returned type of callable is not an instance of interface Result");
90        }
91
92        return $result;
93    }
94
95    /**
96     * @inheritdoc
97     */
98    public function except(callable $f)
99    {
100        return $this;
101    }
102}
103