aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/sabre/event/lib/coroutine.php
blob: cdf2d3ecdb610115ea46cc6be809636cc00f9113 (plain) (blame)
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
<?php

declare(strict_types=1);

namespace Sabre\Event;

use Generator;
use Throwable;

/**
 * Turn asynchronous promise-based code into something that looks synchronous
 * again, through the use of generators.
 *
 * Example without coroutines:
 *
 * $promise = $httpClient->request('GET', '/foo');
 * $promise->then(function($value) {
 *
 *   return $httpClient->request('DELETE','/foo');
 *
 * })->then(function($value) {
 *
 *   return $httpClient->request('PUT', '/foo');
 *
 * })->error(function($reason) {
 *
 *   echo "Failed because: $reason\n";
 *
 * });
 *
 * Example with coroutines:
 *
 * coroutine(function() {
 *
 *   try {
 *     yield $httpClient->request('GET', '/foo');
 *     yield $httpClient->request('DELETE', /foo');
 *     yield $httpClient->request('PUT', '/foo');
 *   } catch(\Throwable $reason) {
 *     echo "Failed because: $reason\n";
 *   }
 *
 * });
 *
 * @return \Sabre\Event\Promise
 *
 * @psalm-template TReturn
 * @psalm-param callable():\Generator<mixed, mixed, mixed, TReturn> $gen
 * @psalm-return Promise<TReturn>
 *
 * @copyright Copyright (C) fruux GmbH (https://fruux.com/)
 * @author Evert Pot (http://evertpot.com/)
 * @license http://sabre.io/license/ Modified BSD License
 */
function coroutine(callable $gen): Promise
{
    $generator = $gen();
    if (!$generator instanceof Generator) {
        throw new \InvalidArgumentException('You must pass a generator function');
    }

    // This is the value we're returning.
    $promise = new Promise();

    /**
     * So tempted to use the mythical y-combinator here, but it's not needed in
     * PHP.
     */
    $advanceGenerator = function () use (&$advanceGenerator, $generator, $promise) {
        while ($generator->valid()) {
            $yieldedValue = $generator->current();
            if ($yieldedValue instanceof Promise) {
                $yieldedValue->then(
                    function ($value) use ($generator, &$advanceGenerator) {
                        $generator->send($value);
                        $advanceGenerator();
                    },
                    function (Throwable $reason) use ($generator, $advanceGenerator) {
                        $generator->throw($reason);
                        $advanceGenerator();
                    }
                )->otherwise(function (Throwable $reason) use ($promise) {
                    // This error handler would be called, if something in the
                    // generator throws an exception, and it's not caught
                    // locally.
                    $promise->reject($reason);
                });
                // We need to break out of the loop, because $advanceGenerator
                // will be called asynchronously when the promise has a result.
                break;
            } else {
                // If the value was not a promise, we'll just let it pass through.
                $generator->send($yieldedValue);
            }
        }

        // If the generator is at the end, and we didn't run into an exception,
        // We're grabbing the "return" value and fulfilling our top-level
        // promise with its value.
        if (!$generator->valid() && Promise::PENDING === $promise->state) {
            $returnValue = $generator->getReturn();

            // The return value is a promise.
            if ($returnValue instanceof Promise) {
                $returnValue->then(function ($value) use ($promise) {
                    $promise->fulfill($value);
                }, function (Throwable $reason) use ($promise) {
                    $promise->reject($reason);
                });
            } else {
                $promise->fulfill($returnValue);
            }
        }
    };

    try {
        $advanceGenerator();
    } catch (Throwable $e) {
        $promise->reject($e);
    }

    return $promise;
}