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

orchestral / workbench / 12403824975

19 Dec 2024 12:31AM UTC coverage: 93.849% (+1.2%) from 92.663%
12403824975

push

github

crynobone
Release 8.15.2

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

595 of 634 relevant lines covered (93.85%)

17.11 hits per line

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

91.52
/src/Console/DevToolCommand.php
1
<?php
2

3
namespace Orchestra\Workbench\Console;
4

5
use Composer\InstalledVersions;
6
use Illuminate\Console\Command;
7
use Illuminate\Contracts\Console\PromptsForMissingInput;
8
use Illuminate\Filesystem\Filesystem;
9
use Illuminate\Support\Arr;
10
use Illuminate\Support\Collection;
11
use Orchestra\Testbench\Foundation\Console\Actions\EnsureDirectoryExists;
12
use Orchestra\Testbench\Foundation\Console\Actions\GeneratesFile;
13
use Orchestra\Workbench\Actions\DumpComposerAutoloads;
14
use Orchestra\Workbench\Actions\ModifyComposer;
15
use Orchestra\Workbench\Events\InstallEnded;
16
use Orchestra\Workbench\Events\InstallStarted;
17
use Orchestra\Workbench\Workbench;
18
use Symfony\Component\Console\Attribute\AsCommand;
19
use Symfony\Component\Console\Input\InputInterface;
20
use Symfony\Component\Console\Input\InputOption;
21
use Symfony\Component\Console\Output\OutputInterface;
22

23
use function Laravel\Prompts\confirm;
24
use function Orchestra\Testbench\join_paths;
25
use function Orchestra\Testbench\package_path;
26

27
#[AsCommand(name: 'workbench:devtool', description: 'Configure Workbench for package development')]
28
class DevToolCommand extends Command implements PromptsForMissingInput
29
{
30
    /**
31
     * Namespace prefix for Workbench environment.
32
     */
33
    protected string $workbenchNamespacePrefix = 'Workbench\\';
34

35
    /**
36
     * Execute the console command.
37
     *
38
     * @return int
39
     */
40
    public function handle(Filesystem $filesystem)
41
    {
42
        $workingPath = package_path();
19✔
43

44
        event(new InstallStarted($this->input, $this->output, $this->components));
19✔
45

46
        $this->prepareWorkbenchNamespaces($filesystem, $workingPath);
19✔
47
        $this->prepareWorkbenchDirectories($filesystem, $workingPath);
19✔
48

49
        if ($this->option('install') === true) {
19✔
50
            $this->call('workbench:install', [
8✔
51
                '--force' => $this->option('force'),
8✔
52
                '--no-devtool' => true,
8✔
53
                '--basic' => $this->option('basic'),
8✔
54
            ]);
8✔
55
        }
56

57
        return tap(Command::SUCCESS, function ($exitCode) use ($workingPath) {
19✔
58
            event(new InstallEnded($this->input, $this->output, $this->components, $exitCode));
19✔
59

60
            (new DumpComposerAutoloads($workingPath))->handle();
19✔
61
        });
19✔
62
    }
63

64
    /**
65
     * Prepare workbench directories.
66
     */
67
    protected function prepareWorkbenchDirectories(Filesystem $filesystem, string $workingPath): void
68
    {
69
        $workbenchWorkingPath = join_paths($workingPath, 'workbench');
19✔
70

71
        (new EnsureDirectoryExists(
19✔
72
            filesystem: $filesystem,
19✔
73
            components: $this->components,
19✔
74
        ))->handle(
19✔
75
            Collection::make([
19✔
76
                join_paths('app', 'Models'),
19✔
77
                join_paths('database', 'factories'),
19✔
78
                join_paths('database', 'migrations'),
19✔
79
                join_paths('database', 'seeders'),
19✔
80
            ])->when(
19✔
81
                $this->option('basic') === false,
19✔
82
                fn ($directories) => $directories->push(...['routes', join_paths('resources', 'views')])
19✔
83
            )->map(static fn ($directory) => join_paths($workbenchWorkingPath, $directory))
19✔
84
        );
19✔
85

86
        $this->callSilently('make:provider', [
19✔
87
            'name' => 'WorkbenchServiceProvider',
19✔
88
            '--preset' => 'workbench',
19✔
89
            '--force' => (bool) $this->option('force'),
19✔
90
        ]);
19✔
91

92
        $this->prepareWorkbenchDatabaseSchema($filesystem, $workbenchWorkingPath);
19✔
93

94
        if ($this->option('basic') === false) {
19✔
95
            foreach (['api', 'console', 'web'] as $route) {
15✔
96
                (new GeneratesFile(
15✔
97
                    filesystem: $filesystem,
15✔
98
                    components: $this->components,
15✔
99
                    force: (bool) $this->option('force'),
15✔
100
                ))->handle(
15✔
101
                    (string) Workbench::stubFile("routes.{$route}"),
15✔
102
                    join_paths($workbenchWorkingPath, 'routes', "{$route}.php")
15✔
103
                );
15✔
104
            }
105
        }
106
    }
107

108
    /**
109
     * Prepare workbench namespace to `composer.json`.
110
     */
111
    protected function prepareWorkbenchNamespaces(Filesystem $filesystem, string $workingPath): void
112
    {
113
        (new ModifyComposer($workingPath))
19✔
114
            ->handle(fn (array $content) => $this->appendScriptsToComposer(
19✔
115
                $this->appendAutoloadDevToComposer($content, $filesystem), $filesystem
19✔
116
            ));
19✔
117

118
        Workbench::flushCachedClassAndNamespaces();
19✔
119
    }
120

121
    /**
122
     * Prepare workbench database schema including user model, factory and seeder.
123
     */
124
    protected function prepareWorkbenchDatabaseSchema(Filesystem $filesystem, string $workingPath): void
125
    {
126
        $this->callSilently('make:user-model', [
19✔
127
            '--preset' => 'workbench',
19✔
128
            '--force' => (bool) $this->option('force'),
19✔
129
        ]);
19✔
130

131
        $this->callSilently('make:user-factory', [
19✔
132
            '--preset' => 'workbench',
19✔
133
            '--force' => (bool) $this->option('force'),
19✔
134
        ]);
19✔
135

136
        (new GeneratesFile(
19✔
137
            filesystem: $filesystem,
19✔
138
            components: $this->components,
19✔
139
            force: (bool) $this->option('force'),
19✔
140
        ))->handle(
19✔
141
            (string) Workbench::stubFile('seeders.database'),
19✔
142
            join_paths($workingPath, 'database', 'seeders', 'DatabaseSeeder.php')
19✔
143
        );
19✔
144

145
        $workbenchSeederNamespacePrefix = rtrim(Workbench::detectNamespace('database/seeders') ?? 'Workbench\Database\Seeders\\', '\\');
19✔
146

147
        $filesystem->replaceInFile([
19✔
148
            '{{WorkbenchSeederNamespace}}',
19✔
149
            '{{ WorkbenchSeederNamespace }}',
19✔
150
            'Workbench\Database\Seeders',
19✔
151
        ], [
19✔
152
            $workbenchSeederNamespacePrefix,
19✔
153
            $workbenchSeederNamespacePrefix,
19✔
154
            $workbenchSeederNamespacePrefix,
19✔
155
        ], join_paths($workingPath, 'database', 'seeders', 'DatabaseSeeder.php'));
19✔
156

157
        if ($filesystem->exists(join_paths($workingPath, 'database', 'factories', 'UserFactory.php'))) {
19✔
158
            $filesystem->replaceInFile([
19✔
159
                'use Orchestra\Testbench\Factories\UserFactory;',
19✔
160
            ], [
19✔
161
                \sprintf('use %sUserFactory;', Workbench::detectNamespace('database/factories') ?? 'Workbench\Database\Factories\\'),
19✔
162
            ], join_paths($workingPath, 'database', 'seeders', 'DatabaseSeeder.php'));
19✔
163
        }
164
    }
165

166
    /**
167
     * Append `scripts` to `composer.json`.
168
     */
169
    protected function appendScriptsToComposer(array $content, Filesystem $filesystem): array
170
    {
171
        $hasScriptsSection = \array_key_exists('scripts', $content);
19✔
172
        $hasTestbenchDusk = InstalledVersions::isInstalled('orchestra/testbench-dusk');
19✔
173

174
        if (! $hasScriptsSection) {
19✔
175
            $content['scripts'] = [];
19✔
176
        }
177

178
        $postAutoloadDumpScripts = array_filter([
19✔
179
            '@clear',
19✔
180
            '@prepare',
19✔
181
            $hasTestbenchDusk ? '@dusk:install-chromedriver' : null,
19✔
182
        ]);
19✔
183

184
        if (! \array_key_exists('post-autoload-dump', $content['scripts'])) {
19✔
185
            $content['scripts']['post-autoload-dump'] = $postAutoloadDumpScripts;
19✔
186
        } else {
187
            $content['scripts']['post-autoload-dump'] = array_values(array_unique([
×
188
                ...$postAutoloadDumpScripts,
×
189
                ...Arr::wrap($content['scripts']['post-autoload-dump']),
×
190
            ]));
×
191
        }
192

193
        $content['scripts']['clear'] = '@php vendor/bin/testbench package:purge-skeleton --ansi';
19✔
194
        $content['scripts']['prepare'] = '@php vendor/bin/testbench package:discover --ansi';
19✔
195

196
        if ($hasTestbenchDusk) {
19✔
197
            $content['scripts']['dusk:install-chromedriver'] = '@php vendor/bin/dusk-updater detect --auto-update --ansi';
×
198
        }
199

200
        $content['scripts']['build'] = '@php vendor/bin/testbench workbench:build --ansi';
19✔
201
        $content['scripts']['serve'] = [
19✔
202
            'Composer\\Config::disableProcessTimeout',
19✔
203
            '@build',
19✔
204
            $hasTestbenchDusk && \defined('TESTBENCH_DUSK')
19✔
205
                ? '@php vendor/bin/testbench-dusk serve --ansi'
×
206
                : '@php vendor/bin/testbench serve --ansi',
19✔
207
        ];
19✔
208

209
        if (! \array_key_exists('lint', $content['scripts'])) {
19✔
210
            $lintScripts = [];
19✔
211

212
            if (InstalledVersions::isInstalled('laravel/pint')) {
19✔
213
                $lintScripts[] = '@php vendor/bin/pint --ansi';
19✔
214
            } elseif ($filesystem->isFile(Workbench::packagePath('pint.json'))) {
×
215
                $lintScripts[] = 'pint';
×
216
            }
217

218
            if (InstalledVersions::isInstalled('phpstan/phpstan')) {
19✔
219
                $lintScripts[] = '@php vendor/bin/phpstan analyse --verbose --ansi';
19✔
220
            }
221

222
            if (\count($lintScripts) > 0) {
19✔
223
                $content['scripts']['lint'] = $lintScripts;
19✔
224
            }
225
        }
226

227
        if (
228
            $filesystem->isFile(Workbench::packagePath('phpunit.xml'))
19✔
229
            || $filesystem->isFile(Workbench::packagePath('phpunit.xml.dist'))
19✔
230
        ) {
231
            if (! \array_key_exists('test', $content['scripts'])) {
19✔
232
                $content['scripts']['test'] = [
19✔
233
                    '@clear',
19✔
234
                    InstalledVersions::isInstalled('pestphp/pest')
19✔
235
                        ? '@php vendor/bin/pest'
×
236
                        : '@php vendor/bin/phpunit',
19✔
237
                ];
19✔
238
            }
239
        }
240

241
        return $content;
19✔
242
    }
243

244
    /**
245
     * Append `autoload-dev` to `composer.json`.
246
     */
247
    protected function appendAutoloadDevToComposer(array $content, Filesystem $filesystem): array
248
    {
249
        /** @var array{autoload-dev?: array{psr-4?: array<string, string>}} $content */
250
        if (! \array_key_exists('autoload-dev', $content)) {
19✔
251
            $content['autoload-dev'] = [];
19✔
252
        }
253

254
        /** @var array{autoload-dev: array{psr-4?: array<string, string>}} $content */
255
        if (! \array_key_exists('psr-4', $content['autoload-dev'])) {
19✔
256
            $content['autoload-dev']['psr-4'] = [];
19✔
257
        }
258

259
        if (confirm('Prefix with `Workbench` namespace?', default: false) === false) {
19✔
260
            $this->workbenchNamespacePrefix = '';
4✔
261
        }
262

263
        $namespaces = [
19✔
264
            'workbench/app/' => $this->workbenchNamespacePrefix.'App\\',
19✔
265
            'workbench/database/factories/' => $this->workbenchNamespacePrefix.'Database\\Factories\\',
19✔
266
            'workbench/database/seeders/' => $this->workbenchNamespacePrefix.'Database\\Seeders\\',
19✔
267
        ];
19✔
268

269
        $autoloads = array_flip($content['autoload-dev']['psr-4']);
19✔
270

271
        foreach ($namespaces as $path => $namespace) {
19✔
272
            if (! \array_key_exists($path, $autoloads)) {
19✔
273
                $content['autoload-dev']['psr-4'][$namespace] = $path;
19✔
274

275
                $this->components->task(\sprintf(
19✔
276
                    'Added [%s] for [%s] to Composer', $namespace, './'.rtrim($path, '/')
19✔
277
                ));
19✔
278
            } else {
279
                $this->components->twoColumnDetail(
×
280
                    \sprintf('Composer already contains [%s] path assigned to [%s] namespace', './'.rtrim($path, '/'), $autoloads[$path]),
×
281
                    '<fg=yellow;options=bold>SKIPPED</>'
×
282
                );
×
283
            }
284
        }
285

286
        return $content;
19✔
287
    }
288

289
    /**
290
     * Prompt the user for any missing arguments.
291
     *
292
     * @return void
293
     */
294
    protected function promptForMissingArguments(InputInterface $input, OutputInterface $output)
295
    {
296
        $install = null;
18✔
297

298
        if ($input->getOption('skip-install') === true) {
18✔
299
            $install = false;
×
300
        } elseif (\is_null($input->getOption('install'))) {
18✔
301
            $install = confirm('Run Workbench installation?', true);
1✔
302
        }
303

304
        if (! \is_null($install)) {
18✔
305
            $input->setOption('install', $install);
1✔
306
        }
307
    }
308

309
    /**
310
     * Get the console command options.
311
     *
312
     * @return array
313
     */
314
    protected function getOptions()
315
    {
316
        return [
19✔
317
            ['force', 'f', InputOption::VALUE_NONE, 'Overwrite any existing files'],
19✔
318
            ['install', null, InputOption::VALUE_NEGATABLE, 'Run Workbench installation'],
19✔
319
            ['basic', null, InputOption::VALUE_NONE, 'Workbench installation without discovers and routes'],
19✔
320

321
            /** @deprecated */
322
            ['skip-install', null, InputOption::VALUE_NONE, 'Skipped Workbench installation (deprecated)'],
19✔
323
        ];
19✔
324
    }
325
}
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

© 2025 Coveralls, Inc