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

orchestral / testbench-core / 14663247932

25 Apr 2025 11:11AM UTC coverage: 92.875% (+0.03%) from 92.844%
14663247932

push

github

web-flow
[8.x] Flush Eloquent states between tests (#338)

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

6 of 6 new or added lines in 1 file covered. (100.0%)

3 existing lines in 1 file now uncovered.

1486 of 1600 relevant lines covered (92.88%)

70.22 hits per line

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

94.57
/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) {
11✔
56
        return $context->make(ConsoleKernel::class)->call($command, $parameters);
1✔
57
    }
58

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

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

64
/**
65
 * Run remote action using Testbench CLI.
66
 *
67
 * @api
68
 *
69
 * @param  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(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
 * Run callback only once.
91
 *
92
 * @api
93
 *
94
 * @param  mixed  $callback
95
 * @return \Closure():mixed
96
 *
97
 * @deprecated 7.55.0 Use `Orchestra\Sidekick\once()` instead.
98
 *
99
 * @codeCoverageIgnore
100
 */
101
function once($callback): Closure
102
{
103
    return Sidekick\once($callback);
104
}
105

106
/**
107
 * Register after resolving callback.
108
 *
109
 * @api
110
 *
111
 * @param  \Illuminate\Contracts\Foundation\Application  $app
112
 * @param  string  $name
113
 * @param  (\Closure(object, \Illuminate\Contracts\Foundation\Application):(mixed))|null  $callback
114
 * @return void
115
 */
116
function after_resolving(ApplicationContract $app, string $name, ?Closure $callback = null): void
117
{
118
    $app->afterResolving($name, $callback);
174✔
119

120
    if ($app->resolved($name)) {
174✔
121
        value($callback, $app->make($name), $app);
5✔
122
    }
123
}
124

125
/**
126
 * Load migration paths.
127
 *
128
 * @api
129
 *
130
 * @param  \Illuminate\Contracts\Foundation\Application  $app
131
 * @param  array<int, string>|string  $paths
132
 * @return void
133
 */
134
function load_migration_paths(ApplicationContract $app, array|string $paths): void
135
{
136
    after_resolving($app, 'migrator', static function ($migrator) use ($paths) {
39✔
137
        foreach (Arr::wrap($paths) as $path) {
16✔
138
            /** @var \Illuminate\Database\Migrations\Migrator $migrator */
139
            $migrator->path($path);
16✔
140
        }
141
    });
39✔
142
}
143

144
/**
145
 * Get default environment variables.
146
 *
147
 * @return array<int, string>
148
 *
149
 * @deprecated
150
 *
151
 * @codeCoverageIgnore
152
 */
153
function default_environment_variables(): array
154
{
155
    return [];
156
}
157

158
/**
159
 * Get defined environment variables.
160
 *
161
 * @api
162
 *
163
 * @return array<string, mixed>
164
 */
165
function defined_environment_variables(): array
166
{
167
    return Collection::make(array_merge($_SERVER, $_ENV))
12✔
168
        ->keys()
12✔
169
        ->mapWithKeys(static fn (string $key) => [$key => Foundation\Env::forward($key)])
12✔
170
        ->unless(
12✔
171
            Foundation\Env::has('TESTBENCH_WORKING_PATH'), static fn ($env) => $env->put('TESTBENCH_WORKING_PATH', package_path())
12✔
172
        )->all();
12✔
173
}
174

175
/**
176
 * Get default environment variables.
177
 *
178
 * @api
179
 *
180
 * @param  iterable<string, mixed>  $variables
181
 * @return array<int, string>
182
 */
183
function parse_environment_variables($variables): array
184
{
185
    return Collection::make($variables)
4✔
186
        ->transform(static function ($value, $key) {
4✔
187
            if (\is_bool($value) || \in_array($value, ['true', 'false'])) {
4✔
188
                $value = \in_array($value, [true, 'true']) ? '(true)' : '(false)';
4✔
189
            } elseif (\is_null($value) || \in_array($value, ['null'])) {
1✔
190
                $value = '(null)';
1✔
191
            } else {
192
                $value = $key === 'APP_DEBUG' ? \sprintf('(%s)', Str::of($value)->ltrim('(')->rtrim(')')) : "'{$value}'";
1✔
193
            }
194

195
            return "{$key}={$value}";
4✔
196
        })->values()->all();
4✔
197
}
198

199
/**
200
 * Refresh router lookups.
201
 *
202
 * @api
203
 *
204
 * @param  \Illuminate\Routing\Router  $router
205
 * @return void
206
 */
207
function refresh_router_lookups(Router $router): void
208
{
209
    $router->getRoutes()->refreshNameLookups();
174✔
210
}
211

212
/**
213
 * Transform realpath to alias path.
214
 *
215
 * @api
216
 *
217
 * @param  string  $path
218
 * @param  string|null  $workingPath
219
 * @return string
220
 */
221
function transform_realpath_to_relative(string $path, ?string $workingPath = null, string $prefix = ''): string
222
{
223
    $separator = DIRECTORY_SEPARATOR;
13✔
224

225
    if (! \is_null($workingPath)) {
13✔
226
        return str_replace(rtrim($workingPath, $separator).$separator, $prefix.$separator, $path);
1✔
227
    }
228

229
    $laravelPath = base_path();
12✔
230
    $workbenchPath = workbench_path();
12✔
231
    $packagePath = package_path();
12✔
232

233
    return match (true) {
234
        str_starts_with($path, $laravelPath) => str_replace($laravelPath.$separator, '@laravel'.$separator, $path),
12✔
235
        str_starts_with($path, $workbenchPath) => str_replace($workbenchPath.$separator, '@workbench'.$separator, $path),
8✔
236
        str_starts_with($path, $packagePath) => str_replace($packagePath.$separator, '.'.$separator, $path),
8✔
237
        ! empty($prefix) => implode($separator, [$prefix, ltrim($path, $separator)]),
8✔
238
        default => $path,
12✔
239
    };
240
}
241

242
/**
243
 * Transform relative path.
244
 *
245
 * @api
246
 *
247
 * @param  string  $path
248
 * @param  string  $workingPath
249
 * @return string
250
 *
251
 * @deprecated 7.55.0 Use `Orchestra\Sidekick\transform_relative_path()` instead.
252
 *
253
 * @codeCoverageIgnore
254
 */
255
function transform_relative_path(string $path, string $workingPath): string
256
{
257
    return Sidekick\transform_relative_path($path, $workingPath);
258
}
259

260
/**
261
 * Get the default skeleton path.
262
 *
263
 * @api
264
 *
265
 * @no-named-arguments
266
 *
267
 * @param  array<int, string|null>|string  ...$path
268
 * @return string
269
 */
270
function default_skeleton_path(array|string $path = ''): string
271
{
272
    return (string) realpath(
171✔
273
        Sidekick\join_paths(__DIR__, '..', 'laravel', ...Arr::wrap(\func_num_args() > 1 ? \func_get_args() : $path))
171✔
274
    );
171✔
275
}
276

277
/**
278
 * Get the migration path by type.
279
 *
280
 * @api
281
 *
282
 * @param  string|null  $type
283
 * @return string
284
 *
285
 * @throws \InvalidArgumentException
286
 */
287
function default_migration_path(?string $type = null): string
288
{
289
    $path = realpath(
46✔
290
        \is_null($type) ? base_path('migrations') : base_path(Sidekick\join_paths('migrations', $type))
46✔
291
    );
46✔
292

293
    if ($path === false) {
46✔
UNCOV
294
        throw new InvalidArgumentException(\sprintf('Unable to resolve migration path for type [%s]', $type ?? 'laravel'));
×
295
    }
296

297
    return $path;
46✔
298
}
299

300
/**
301
 * Get the path to the package folder.
302
 *
303
 * @api
304
 *
305
 * @no-named-arguments
306
 *
307
 * @param  array<int, string|null>|string  ...$path
308
 * @return string
309
 */
310
function package_path(array|string $path = ''): string
311
{
312
    $argumentCount = \func_num_args();
79✔
313

314
    $workingPath = \defined('TESTBENCH_WORKING_PATH')
79✔
315
        ? TESTBENCH_WORKING_PATH
43✔
316
        : Foundation\Env::get('TESTBENCH_WORKING_PATH', getcwd());
36✔
317

318
    if ($argumentCount === 1 && \is_string($path) && str_starts_with($path, './')) {
79✔
319
        return transform_relative_path($path, $workingPath);
7✔
320
    }
321

322
    $path = Sidekick\join_paths(...Arr::wrap($argumentCount > 1 ? \func_get_args() : $path));
79✔
323

324
    return str_starts_with($path, './')
79✔
UNCOV
325
        ? transform_relative_path($path, $workingPath)
×
326
        : Sidekick\join_paths(rtrim($workingPath, DIRECTORY_SEPARATOR), $path);
79✔
327
}
328

329
/**
330
 * Get the workbench configuration.
331
 *
332
 * @api
333
 *
334
 * @return array<string, mixed>
335
 */
336
function workbench(): array
337
{
338
    /** @var \Orchestra\Testbench\Contracts\Config $config */
339
    $config = app()->bound(Contracts\Config::class)
36✔
340
        ? app()->make(Contracts\Config::class)
34✔
341
        : new Foundation\Config;
2✔
342

343
    return $config->getWorkbenchAttributes();
36✔
344
}
345

346
/**
347
 * Get the path to the workbench folder.
348
 *
349
 * @api
350
 *
351
 * @no-named-arguments
352
 *
353
 * @param  array<int, string|null>|string  ...$path
354
 * @return string
355
 */
356
function workbench_path(array|string $path = ''): string
357
{
358
    return package_path('workbench', ...Arr::wrap(\func_num_args() > 1 ? \func_get_args() : $path));
62✔
359
}
360

361
/**
362
 * Get the migration path by type.
363
 *
364
 * @api
365
 *
366
 * @param  string|null  $type
367
 * @return string
368
 *
369
 * @throws \InvalidArgumentException
370
 *
371
 * @deprecated
372
 */
373
function laravel_migration_path(?string $type = null): string
374
{
375
    return default_migration_path($type);
1✔
376
}
377

378
/**
379
 * Determine if vendor symlink exists on the laravel application.
380
 *
381
 * @api
382
 *
383
 * @param  \Illuminate\Contracts\Foundation\Application  $app
384
 * @param  string|null  $workingPath
385
 * @return bool
386
 */
387
function laravel_vendor_exists(ApplicationContract $app, ?string $workingPath = null): bool
388
{
389
    $filesystem = new Filesystem;
11✔
390

391
    $appVendorPath = $app->basePath('vendor');
11✔
392
    $workingPath ??= package_path('vendor');
11✔
393

394
    return $filesystem->isFile(join_paths($appVendorPath, 'autoload.php')) &&
11✔
395
        $filesystem->hash(join_paths($appVendorPath, 'autoload.php')) === $filesystem->hash(join_paths($workingPath, 'autoload.php'));
11✔
396
}
397

398
/**
399
 * Laravel version compare.
400
 *
401
 * @api
402
 *
403
 * @template TOperator of string|null
404
 *
405
 * @param  string  $version
406
 * @param  string|null  $operator
407
 * @return int|bool
408
 *
409
 * @phpstan-param  TOperator  $operator
410
 *
411
 * @phpstan-return (TOperator is null ? int : bool)
412
 */
413
function laravel_version_compare(string $version, ?string $operator = null)
414
{
415
    return Sidekick\laravel_version_compare($version, $operator);
1✔
416
}
417

418
/**
419
 * PHPUnit version compare.
420
 *
421
 * @api
422
 *
423
 * @template TOperator of string|null
424
 *
425
 * @param  string  $version
426
 * @param  string|null  $operator
427
 * @return int|bool
428
 *
429
 * @throws \RuntimeException
430
 *
431
 * @phpstan-param  TOperator  $operator
432
 *
433
 * @phpstan-return (TOperator is null ? int : bool)
434
 */
435
function phpunit_version_compare(string $version, ?string $operator = null)
436
{
437
    return Sidekick\phpunit_version_compare($version, $operator);
1✔
438
}
439

440
/**
441
 * Determine the PHP Binary.
442
 *
443
 * @api
444
 *
445
 * @param  bool  $escape
446
 * @return string
447
 */
448
function php_binary(bool $escape = false): string
449
{
450
    $phpBinary = Sidekick\php_binary();
12✔
451

452
    return $escape === true ? ProcessUtils::escapeArgument((string) $phpBinary) : $phpBinary;
12✔
453
}
454

455
/**
456
 * Join the given paths together.
457
 *
458
 * @param  string|null  $basePath
459
 * @param  string  ...$paths
460
 * @return string
461
 *
462
 * @codeCoverageIgnore
463
 */
464
function join_paths(?string $basePath, string ...$paths): string
465
{
466
    return Sidekick\join_paths($basePath, ...$paths);
467
}
468

469
/**
470
 * Ensure the provided `$app` return an instance of Laravel application or throw an exception.
471
 *
472
 * @internal
473
 *
474
 * @param  \Illuminate\Foundation\Application|null  $app
475
 * @param  string|null  $caller
476
 * @return \Illuminate\Foundation\Application
477
 *
478
 * @throws \Orchestra\Testbench\Exceptions\ApplicationNotAvailableException
479
 */
480
function laravel_or_fail($app, ?string $caller = null): Application
481
{
482
    if ($app instanceof Application) {
168✔
483
        return $app;
168✔
484
    }
485

486
    if (\is_null($caller)) {
1✔
487
        $caller = transform(debug_backtrace()[1] ?? null, function ($debug) {
1✔
488
            /** @phpstan-ignore isset.offset */
489
            if (isset($debug['class']) && isset($debug['function'])) {
1✔
490
                return \sprintf('%s::%s', $debug['class'], $debug['function']);
1✔
491
            }
492

493
            /** @phpstan-ignore offsetAccess.notFound */
UNCOV
494
            return $debug['function'];
×
495
        });
1✔
496
    }
497

498
    throw Exceptions\ApplicationNotAvailableException::make($caller);
1✔
499
}
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