Skip to content

Commit 4f52883

Browse files
author
Thibault GRANADA
committed
[Model] Allow to pass closure to resolve API provider
1 parent dad8db2 commit 4f52883

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

src/Model.php

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace Cristal\ApiWrapper;
44

55
use ArrayAccess;
6+
use Closure;
67
use Cristal\ApiWrapper\Concerns\HasAttributes;
78
use Cristal\ApiWrapper\Concerns\HasRelationships;
89
use Cristal\ApiWrapper\Concerns\HasGlobalScopes;
@@ -71,9 +72,9 @@ abstract class Model implements ArrayAccess, JsonSerializable
7172
/**
7273
* Set the Model Api.
7374
*
74-
* @param Api $api
75+
* @param Api|Closure $api
7576
*/
76-
public static function setApi(Api $api)
77+
public static function setApi($api)
7778
{
7879
static::$apis[static::$api] = $api;
7980
}
@@ -85,11 +86,21 @@ public static function setApi(Api $api)
8586
*/
8687
public function getApi(): Api
8788
{
88-
if (static::$apis[static::$api] ?? null) {
89-
return static::$apis[static::$api];
89+
if (!static::$apis[static::$api] ?? null) {
90+
throw new MissingApiException();
9091
}
9192

92-
throw new MissingApiException();
93+
$api = static::$apis[static::$api];
94+
95+
if (is_callable($api)) {
96+
$api = $api();
97+
}
98+
99+
if (!$api instanceof Api) {
100+
throw new MissingApiException();
101+
}
102+
103+
return $api;
93104
}
94105

95106
/**

0 commit comments

Comments
 (0)