Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
3 / 3
CRAP
n/a
0 / 0
FastForward\Defer\defer
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
FastForward\Defer\using
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
FastForward\Defer\scope
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5/**
6 * This file is part of fast-forward/defer.
7 *
8 * This source file is subject to the license bundled
9 * with this source code in the file LICENSE.
10 *
11 * @copyright Copyright (c) 2026 Felipe SayĆ£o Lobato Abreu <github@mentordosnerds.com>
12 * @license   https://opensource.org/licenses/MIT MIT License
13 *
14 * @see       https://github.com/php-fast-forward/defer
15 * @see       https://github.com/php-fast-forward
16 * @see       https://datatracker.ietf.org/doc/html/rfc2119
17 */
18
19namespace FastForward\Defer;
20
21/**
22 * Creates a new Defer instance, optionally registering a callback immediately.
23 *
24 * This function MUST return a DeferInterface implementation. If a callback is provided, it SHALL be registered.
25 *
26 * @param callable|null $callback the callback to register (optional)
27 * @param mixed ...$arguments Arguments for the callback.
28 *
29 * @return DeferInterface the Defer instance
30 */
31function defer(?callable $callback = null, mixed ...$arguments): DeferInterface
32{
33    return new Defer($callback, ...$arguments);
34}
35
36/**
37 * Executes a callback within a controlled scope, ensuring resources are released at the end.
38 *
39 * This function MUST create a Defer instance, pass it to the factory, and execute the callback.
40 * The Defer instance SHALL be unset after execution.
41 *
42 * @param callable $factory a function that receives the Defer and returns the resource
43 * @param callable $callback a function that receives the resource and executes the desired logic
44 *
45 * @return mixed the return value of the callback
46 */
47function using(callable $factory, callable $callback): mixed
48{
49    $defer = defer();
50
51    try {
52        return $callback($factory($defer));
53    } finally {
54        unset($defer);
55    }
56}
57
58/**
59 * Executes a callback within a deferred scope, ensuring all registered callbacks are executed at the end.
60 *
61 * This function MUST create a Defer instance, pass it to the callback, and unset it after execution.
62 *
63 * @param callable $callback a function that receives the Defer and executes the desired logic
64 *
65 * @return mixed the return value of the callback
66 */
67function scope(callable $callback): mixed
68{
69    $defer = defer();
70
71    try {
72        return $callback($defer);
73    } finally {
74        unset($defer);
75    }
76}