• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

orchestral / testbench-core / 14289826616

06 Apr 2025 06:26AM UTC coverage: 92.421% (+0.01%) from 92.411%
14289826616

push

github

crynobone
Release 10.2.0

Signed-off-by: Mior Muhammad Zaki <crynobone@gmail.com>

1512 of 1636 relevant lines covered (92.42%)

74.53 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

94.38
/src/functions.php
1
<?php
2

3
namespace Orchestra\Testbench;
4

5
use Closure;
6
use Illuminate\Contracts\Console\Kernel as ConsoleKernel;
7
use Illuminate\Contracts\Foundation\Application as ApplicationContract;
8
use Illuminate\Filesystem\Filesystem;
9
use Illuminate\Foundation\Application;
10
use Illuminate\Routing\Router;
11
use Illuminate\Support\Arr;
12
use Illuminate\Support\Collection;
13
use Illuminate\Support\ProcessUtils;
14
use Illuminate\Support\Str;
15
use Illuminate\Testing\PendingCommand;
16
use InvalidArgumentException;
17
use Orchestra\Sidekick;
18

19
/**
20
 * Create Laravel application instance.
21
 *
22
 * @api
23
 *
24
 * @param  string|null  $basePath
25
 * @param  (callable(\Illuminate\Foundation\Application):(void))|null  $resolvingCallback
26
 * @param  array{extra?: array{providers?: array, dont-discover?: array, env?: array}, load_environment_variables?: bool, enabled_package_discoveries?: bool}  $options
27
 * @param  \Orchestra\Testbench\Foundation\Config|null  $config
28
 * @return \Orchestra\Testbench\Foundation\Application
29
 */
30
function container(
31
    ?string $basePath = null,
32
    ?callable $resolvingCallback = null,
33
    array $options = [],
34
    ?Foundation\Config $config = null
35
): Foundation\Application {
36
    if ($config instanceof Foundation\Config) {
3✔
37
        return Foundation\Application::makeFromConfig($config, $resolvingCallback, $options);
×
38
    }
39

40
    return Foundation\Application::make($basePath, $resolvingCallback, $options);
3✔
41
}
42

43
/**
44
 * Run artisan command.
45
 *
46
 * @api
47
 *
48
 * @param  \Orchestra\Testbench\Contracts\TestCase|\Illuminate\Contracts\Foundation\Application  $context
49
 * @param  string  $command
50
 * @param  array<string, mixed>  $parameters
51
 * @return int
52
 */
53
function artisan(Contracts\TestCase|ApplicationContract $context, string $command, array $parameters = []): int
54
{
55
    if ($context instanceof ApplicationContract) {
15✔
56
        return $context->make(ConsoleKernel::class)->call($command, $parameters);
1✔
57
    }
58

59
    $command = $context->artisan($command, $parameters);
15✔
60

61
    return $command instanceof PendingCommand ? $command->run() : $command;
15✔
62
}
63

64
/**
65
 * Run remote action using Testbench CLI.
66
 *
67
 * @api
68
 *
69
 * @param  (\Closure():(mixed))|array<int, string>|string  $command
70
 * @param  array<string, mixed>|string  $env
71
 * @param  bool|null  $tty
72
 * @return \Orchestra\Testbench\Foundation\Process\ProcessDecorator
73
 */
74
function remote(Closure|array|string $command, array|string $env = [], ?bool $tty = null): Foundation\Process\ProcessDecorator
75
{
76
    $remote = new Foundation\Process\RemoteCommand(
12✔
77
        package_path(), $env, $tty
12✔
78
    );
12✔
79

80
    $binary = \defined('TESTBENCH_DUSK') ? 'testbench-dusk' : 'testbench';
12✔
81

82
    $commander = is_file($vendorBinary = package_path('vendor', 'bin', $binary))
12✔
83
        ? $vendorBinary
×
84
        : $binary;
12✔
85

86
    return $remote->handle($commander, $command);
12✔
87
}
88

89
/**
90
 * Register after resolving callback.
91
 *
92
 * @api
93
 *
94
 * @param  \Illuminate\Contracts\Foundation\Application  $app
95
 * @param  string  $name
96
 * @param  (\Closure(object, \Illuminate\Contracts\Foundation\Application):(mixed))|null  $callback
97
 * @return void
98
 */
99
function after_resolving(ApplicationContract $app, string $name, ?Closure $callback = null): void
100
{
101
    $app->afterResolving($name, $callback);
193✔
102

103
    if ($app->resolved($name)) {
193✔
104
        value($callback, $app->make($name), $app);
1✔
105
    }
106
}
107

108
/**
109
 * Load migration paths.
110
 *
111
 * @api
112
 *
113
 * @param  \Illuminate\Contracts\Foundation\Application  $app
114
 * @param  array<int, string>|string  $paths
115
 * @return void
116
 */
117
function load_migration_paths(ApplicationContract $app, array|string $paths): void
118
{
119
    after_resolving($app, 'migrator', static function ($migrator) use ($paths) {
51✔
120
        foreach (Arr::wrap($paths) as $path) {
15✔
121
            /** @var \Illuminate\Database\Migrations\Migrator $migrator */
122
            $migrator->path($path);
15✔
123
        }
124
    });
51✔
125
}
126

127
/**
128
 * Get defined environment variables.
129
 *
130
 * @api
131
 *
132
 * @return array<string, mixed>
133
 */
134
function defined_environment_variables(): array
135
{
136
    return Collection::make(array_merge($_SERVER, $_ENV))
12✔
137
        ->keys()
12✔
138
        ->mapWithKeys(static fn (string $key) => [$key => Foundation\Env::forward($key)])
12✔
139
        ->unless(
12✔
140
            Foundation\Env::has('TESTBENCH_WORKING_PATH'), static fn ($env) => $env->put('TESTBENCH_WORKING_PATH', package_path())
12✔
141
        )->all();
12✔
142
}
143

144
/**
145
 * Get default environment variables.
146
 *
147
 * @api
148
 *
149
 * @param  iterable<string, mixed>  $variables
150
 * @return array<int, string>
151
 */
152
function parse_environment_variables($variables): array
153
{
154
    return Collection::make($variables)
4✔
155
        ->transform(static function ($value, $key) {
4✔
156
            if (\is_bool($value) || \in_array($value, ['true', 'false'])) {
4✔
157
                $value = \in_array($value, [true, 'true']) ? '(true)' : '(false)';
4✔
158
            } elseif (\is_null($value) || \in_array($value, ['null'])) {
1✔
159
                $value = '(null)';
1✔
160
            } else {
161
                $value = $key === 'APP_DEBUG' ? \sprintf('(%s)', Str::of($value)->ltrim('(')->rtrim(')')) : "'{$value}'";
1✔
162
            }
163

164
            return "{$key}={$value}";
4✔
165
        })->values()->all();
4✔
166
}
167

168
/**
169
 * Refresh router lookups.
170
 *
171
 * @api
172
 *
173
 * @param  \Illuminate\Routing\Router  $router
174
 * @return void
175
 */
176
function refresh_router_lookups(Router $router): void
177
{
178
    $router->getRoutes()->refreshNameLookups();
193✔
179
}
180

181
/**
182
 * Transform realpath to alias path.
183
 *
184
 * @api
185
 *
186
 * @param  string  $path
187
 * @param  string|null  $workingPath
188
 * @return string
189
 */
190
function transform_realpath_to_relative(string $path, ?string $workingPath = null, string $prefix = ''): string
191
{
192
    $separator = DIRECTORY_SEPARATOR;
13✔
193

194
    if (! \is_null($workingPath)) {
13✔
195
        return str_replace(rtrim($workingPath, $separator).$separator, $prefix.$separator, $path);
1✔
196
    }
197

198
    $laravelPath = base_path();
12✔
199
    $workbenchPath = workbench_path();
12✔
200
    $packagePath = package_path();
12✔
201

202
    return match (true) {
203
        str_starts_with($path, $laravelPath) => str_replace($laravelPath.$separator, '@laravel'.$separator, $path),
12✔
204
        str_starts_with($path, $workbenchPath) => str_replace($workbenchPath.$separator, '@workbench'.$separator, $path),
8✔
205
        str_starts_with($path, $packagePath) => str_replace($packagePath.$separator, '.'.$separator, $path),
8✔
206
        ! empty($prefix) => implode($separator, [$prefix, ltrim($path, $separator)]),
8✔
207
        default => $path,
12✔
208
    };
209
}
210

211
/**
212
 * Get the default skeleton path.
213
 *
214
 * @api
215
 *
216
 * @no-named-arguments
217
 *
218
 * @param  array<int, string|null>|string  ...$path
219
 * @return string
220
 */
221
function default_skeleton_path(array|string $path = ''): string
222
{
223
    return (string) realpath(
190✔
224
        Sidekick\join_paths(__DIR__, '..', 'laravel', ...Arr::wrap(\func_num_args() > 1 ? \func_get_args() : $path))
190✔
225
    );
190✔
226
}
227

228
/**
229
 * Get the migration path by type.
230
 *
231
 * @api
232
 *
233
 * @param  string|null  $type
234
 * @return string
235
 *
236
 * @throws \InvalidArgumentException
237
 */
238
function default_migration_path(?string $type = null): string
239
{
240
    $path = realpath(
58✔
241
        \is_null($type) ? base_path('migrations') : base_path(Sidekick\join_paths('migrations', $type))
58✔
242
    );
58✔
243

244
    if ($path === false) {
58✔
245
        throw new InvalidArgumentException(\sprintf('Unable to resolve migration path for type [%s]', $type ?? 'laravel'));
×
246
    }
247

248
    return $path;
58✔
249
}
250

251
/**
252
 * Get the path to the package folder.
253
 *
254
 * @api
255
 *
256
 * @no-named-arguments
257
 *
258
 * @param  array<int, string|null>|string  ...$path
259
 * @return string
260
 */
261
function package_path(array|string $path = ''): string
262
{
263
    $argumentCount = \func_num_args();
93✔
264

265
    $workingPath = \defined('TESTBENCH_WORKING_PATH')
93✔
266
        ? TESTBENCH_WORKING_PATH
54✔
267
        : Foundation\Env::get('TESTBENCH_WORKING_PATH', getcwd());
39✔
268

269
    if ($argumentCount === 1 && \is_string($path) && str_starts_with($path, './')) {
93✔
270
        return Sidekick\transform_relative_path($path, $workingPath);
7✔
271
    }
272

273
    $path = Sidekick\join_paths(...Arr::wrap($argumentCount > 1 ? \func_get_args() : $path));
93✔
274

275
    return str_starts_with($path, './')
93✔
276
        ? Sidekick\transform_relative_path($path, $workingPath)
×
277
        : Sidekick\join_paths(rtrim($workingPath, DIRECTORY_SEPARATOR), $path);
93✔
278
}
279

280
/**
281
 * Get the workbench configuration.
282
 *
283
 * @api
284
 *
285
 * @return array<string, mixed>
286
 */
287
function workbench(): array
288
{
289
    /** @var \Orchestra\Testbench\Contracts\Config $config */
290
    $config = app()->bound(Contracts\Config::class)
48✔
291
        ? app()->make(Contracts\Config::class)
46✔
292
        : new Foundation\Config;
2✔
293

294
    return $config->getWorkbenchAttributes();
48✔
295
}
296

297
/**
298
 * Get the path to the workbench folder.
299
 *
300
 * @api
301
 *
302
 * @no-named-arguments
303
 *
304
 * @param  array<int, string|null>|string  ...$path
305
 * @return string
306
 */
307
function workbench_path(array|string $path = ''): string
308
{
309
    return package_path('workbench', ...Arr::wrap(\func_num_args() > 1 ? \func_get_args() : $path));
74✔
310
}
311

312
/**
313
 * Get the migration path by type.
314
 *
315
 * @api
316
 *
317
 * @param  string|null  $type
318
 * @return string
319
 *
320
 * @throws \InvalidArgumentException
321
 *
322
 * @deprecated
323
 *
324
 * @codeCoverageIgnore
325
 */
326
#[\Deprecated(message: 'Use `Orchestra\Testbench\default_migration_path()` instead', since: '9.5.1')]
327
function laravel_migration_path(?string $type = null): string
328
{
329
    return default_migration_path($type);
330
}
331

332
/**
333
 * Determine if vendor symlink exists on the laravel application.
334
 *
335
 * @api
336
 *
337
 * @param  \Illuminate\Contracts\Foundation\Application  $app
338
 * @param  string|null  $workingPath
339
 * @return bool
340
 */
341
function laravel_vendor_exists(ApplicationContract $app, ?string $workingPath = null): bool
342
{
343
    $filesystem = new Filesystem;
11✔
344

345
    $appVendorPath = $app->basePath('vendor');
11✔
346
    $workingPath ??= package_path('vendor');
11✔
347

348
    return $filesystem->isFile(Sidekick\join_paths($appVendorPath, 'autoload.php')) &&
11✔
349
        $filesystem->hash(Sidekick\join_paths($appVendorPath, 'autoload.php')) === $filesystem->hash(Sidekick\join_paths($workingPath, 'autoload.php'));
11✔
350
}
351

352
/**
353
 * Laravel version compare.
354
 *
355
 * @api
356
 *
357
 * @template TOperator of string|null
358
 *
359
 * @param  string  $version
360
 * @param  string|null  $operator
361
 * @return int|bool
362
 *
363
 * @phpstan-param  TOperator  $operator
364
 *
365
 * @phpstan-return (TOperator is null ? int : bool)
366
 *
367
 * @codeCoverageIgnore
368
 */
369
function laravel_version_compare(string $version, ?string $operator = null): int|bool
370
{
371
    return Sidekick\laravel_version_compare($version, $operator);
372
}
373

374
/**
375
 * PHPUnit version compare.
376
 *
377
 * @api
378
 *
379
 * @template TOperator of string|null
380
 *
381
 * @param  string  $version
382
 * @param  string|null  $operator
383
 * @return int|bool
384
 *
385
 * @throws \RuntimeException
386
 *
387
 * @phpstan-param  TOperator  $operator
388
 *
389
 * @phpstan-return (TOperator is null ? int : bool)
390
 *
391
 * @codeCoverageIgnore
392
 */
393
function phpunit_version_compare(string $version, ?string $operator = null): int|bool
394
{
395
    return Sidekick\phpunit_version_compare($version, $operator);
396
}
397

398
/**
399
 * Determine the PHP Binary.
400
 *
401
 * @api
402
 *
403
 * @param  bool  $escape
404
 * @return string
405
 */
406
function php_binary(bool $escape = false): string
407
{
408
    $phpBinary = Sidekick\php_binary();
12✔
409

410
    return $escape === true ? ProcessUtils::escapeArgument((string) $phpBinary) : $phpBinary;
12✔
411
}
412

413
/**
414
 * Join the given paths together.
415
 *
416
 * @param  string|null  $basePath
417
 * @param  string  ...$paths
418
 * @return string
419
 *
420
 * @codeCoverageIgnore
421
 */
422
function join_paths(?string $basePath, string ...$paths): string
423
{
424
    return Sidekick\join_paths($basePath, ...$paths);
425
}
426

427
/**
428
 * Ensure the provided `$app` return an instance of Laravel application or throw an exception.
429
 *
430
 * @internal
431
 *
432
 * @param  \Illuminate\Foundation\Application|null  $app
433
 * @param  string|null  $caller
434
 * @return \Illuminate\Foundation\Application
435
 *
436
 * @throws \Orchestra\Testbench\Exceptions\ApplicationNotAvailableException
437
 */
438
function laravel_or_fail($app, ?string $caller = null): Application
439
{
440
    if ($app instanceof Application) {
187✔
441
        return $app;
187✔
442
    }
443

444
    if (\is_null($caller)) {
1✔
445
        $caller = transform(debug_backtrace()[1] ?? null, function ($debug) {
1✔
446
            /** @phpstan-ignore isset.offset */
447
            if (isset($debug['class']) && isset($debug['function'])) {
1✔
448
                return \sprintf('%s::%s', $debug['class'], $debug['function']);
1✔
449
            }
450

451
            /** @phpstan-ignore offsetAccess.notFound */
452
            return $debug['function'];
×
453
        });
1✔
454
    }
455

456
    throw Exceptions\ApplicationNotAvailableException::make($caller);
1✔
457
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc