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

orchestral / workbench / 12402649321

18 Dec 2024 10:48PM UTC coverage: 91.602% (+0.01%) from 91.589%
12402649321

Pull #69

github

web-flow
Merge 57172861e into c490ec92a
Pull Request #69: Fixes generated namespace via `workbench:install`

3 of 4 new or added lines in 2 files covered. (75.0%)

23 existing lines in 2 files now uncovered.

589 of 643 relevant lines covered (91.6%)

14.92 hits per line

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

87.1
/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();
15✔
43

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

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

49
        if ($this->option('install') === true) {
15✔
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) {
15✔
58
            event(new InstallEnded($this->input, $this->output, $this->components, $exitCode));
15✔
59

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

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

71
        (new EnsureDirectoryExists(
15✔
72
            filesystem: $filesystem,
15✔
73
            components: $this->components,
15✔
74
        ))->handle(
15✔
75
            Collection::make([
15✔
76
                join_paths('app', 'Models'),
15✔
77

78
                join_paths('database', 'factories'),
15✔
79
                join_paths('database', 'migrations'),
15✔
80
                join_paths('database', 'seeders'),
15✔
81
            ])->when(
15✔
82
                $this->option('basic') === false,
15✔
83
                fn ($directories) => $directories->push(...['bootstrap', 'routes', join_paths('resources', 'views')])
15✔
84
            )->map(static fn ($directory) => join_paths($workbenchWorkingPath, $directory))
15✔
85
        );
15✔
86

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

93
        $this->prepareWorkbenchDatabaseSchema($filesystem, $workbenchWorkingPath);
15✔
94

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

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

119
        Workbench::flushCachedClassAndNamespaces();
15✔
120
    }
121

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

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

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

146
        if ($filesystem->exists(join_paths($workingPath, 'database', 'factories', 'UserFactory.php'))) {
15✔
147
            $filesystem->replaceInFile([
15✔
148
                'use Orchestra\Testbench\Factories\UserFactory;',
15✔
149
            ], [
15✔
150
                sprintf('use %sUserFactory;', Workbench::detectNamespace('database/factories') ?? 'Workbench\Database\Factories\\'),
15✔
151
            ], join_paths($workingPath, 'database', 'seeders', 'DatabaseSeeder.php'));
15✔
152
        }
153
    }
154

155
    /**
156
     * Append `scripts` to `composer.json`.
157
     */
158
    protected function appendScriptsToComposer(array $content, Filesystem $filesystem): array
159
    {
160
        $hasScriptsSection = \array_key_exists('scripts', $content);
15✔
161
        $hasTestbenchDusk = InstalledVersions::isInstalled('orchestra/testbench-dusk');
15✔
162

163
        if (! $hasScriptsSection) {
15✔
164
            $content['scripts'] = [];
15✔
165
        }
166

167
        $postAutoloadDumpScripts = array_filter([
15✔
168
            '@clear',
15✔
169
            '@prepare',
15✔
170
            $hasTestbenchDusk ? '@dusk:install-chromedriver' : null,
15✔
171
        ]);
15✔
172

173
        if (! \array_key_exists('post-autoload-dump', $content['scripts'])) {
15✔
174
            $content['scripts']['post-autoload-dump'] = $postAutoloadDumpScripts;
15✔
175
        } else {
UNCOV
176
            $content['scripts']['post-autoload-dump'] = array_values(array_unique([
×
UNCOV
177
                ...$postAutoloadDumpScripts,
×
UNCOV
178
                ...Arr::wrap($content['scripts']['post-autoload-dump']),
×
UNCOV
179
            ]));
×
180
        }
181

182
        $content['scripts']['clear'] = '@php vendor/bin/testbench package:purge-skeleton --ansi';
15✔
183
        $content['scripts']['prepare'] = '@php vendor/bin/testbench package:discover --ansi';
15✔
184

185
        if ($hasTestbenchDusk) {
15✔
UNCOV
186
            $content['scripts']['dusk:install-chromedriver'] = '@php vendor/bin/dusk-updater detect --auto-update --ansi';
×
187
        }
188

189
        $content['scripts']['build'] = '@php vendor/bin/testbench workbench:build --ansi';
15✔
190
        $content['scripts']['serve'] = [
15✔
191
            'Composer\\Config::disableProcessTimeout',
15✔
192
            '@build',
15✔
193
            $hasTestbenchDusk && \defined('TESTBENCH_DUSK')
15✔
UNCOV
194
                ? '@php vendor/bin/testbench-dusk serve --ansi'
×
195
                : '@php vendor/bin/testbench serve --ansi',
15✔
196
        ];
15✔
197

198
        if (! \array_key_exists('lint', $content['scripts'])) {
15✔
199
            $lintScripts = [];
15✔
200

201
            if (InstalledVersions::isInstalled('laravel/pint')) {
15✔
202
                $lintScripts[] = '@php vendor/bin/pint --ansi';
15✔
UNCOV
203
            } elseif ($filesystem->isFile(Workbench::packagePath('pint.json'))) {
×
UNCOV
204
                $lintScripts[] = 'pint';
×
205
            }
206

207
            if (InstalledVersions::isInstalled('phpstan/phpstan')) {
15✔
208
                $lintScripts[] = '@php vendor/bin/phpstan analyse --verbose --ansi';
15✔
209
            }
210

211
            if (\count($lintScripts) > 0) {
15✔
212
                $content['scripts']['lint'] = $lintScripts;
15✔
213
            }
214
        }
215

216
        if (
217
            $filesystem->isFile(Workbench::packagePath('phpunit.xml'))
15✔
218
            || $filesystem->isFile(Workbench::packagePath('phpunit.xml.dist'))
15✔
219
        ) {
UNCOV
220
            if (! \array_key_exists('test', $content['scripts'])) {
×
UNCOV
221
                $content['scripts']['test'] = [
×
UNCOV
222
                    '@clear',
×
UNCOV
223
                    InstalledVersions::isInstalled('pestphp/pest')
×
UNCOV
224
                        ? '@php vendor/bin/pest'
×
UNCOV
225
                        : '@php vendor/bin/phpunit',
×
UNCOV
226
                ];
×
227
            }
228
        }
229

230
        return $content;
15✔
231
    }
232

233
    /**
234
     * Append `autoload-dev` to `composer.json`.
235
     */
236
    protected function appendAutoloadDevToComposer(array $content, Filesystem $filesystem): array
237
    {
238
        /** @var array{autoload-dev?: array{psr-4?: array<string, string>}} $content */
239
        if (! \array_key_exists('autoload-dev', $content)) {
15✔
240
            $content['autoload-dev'] = [];
15✔
241
        }
242

243
        /** @var array{autoload-dev: array{psr-4?: array<string, string>}} $content */
244
        if (! \array_key_exists('psr-4', $content['autoload-dev'])) {
15✔
245
            $content['autoload-dev']['psr-4'] = [];
15✔
246
        }
247

248
        if (confirm('Prefix with `Workbench` namespace?', default: false) === false) {
15✔
249
            $this->workbenchNamespacePrefix = '';
1✔
250
        }
251

252
        $namespaces = [
15✔
253
            'workbench/app/' => $this->workbenchNamespacePrefix.'App\\',
15✔
254
            'workbench/database/factories/' => $this->workbenchNamespacePrefix.'Database\\Factories\\',
15✔
255
            'workbench/database/seeders/' => $this->workbenchNamespacePrefix.'Database\\Seeders\\',
15✔
256
        ];
15✔
257

258
        $autoloads = array_flip($content['autoload-dev']['psr-4']);
15✔
259

260
        foreach ($namespaces as $path => $namespace) {
15✔
261
            if (! \array_key_exists($path, $autoloads)) {
15✔
262
                $content['autoload-dev']['psr-4'][$namespace] = $path;
15✔
263

264
                $this->components->task(\sprintf(
15✔
265
                    'Added [%s] for [%s] to Composer', $namespace, './'.rtrim($path, '/')
15✔
266
                ));
15✔
267
            } else {
UNCOV
268
                $this->components->twoColumnDetail(
×
UNCOV
269
                    \sprintf('Composer already contains [%s] path assigned to [%s] namespace', './'.rtrim($path, '/'), $autoloads[$path]),
×
UNCOV
270
                    '<fg=yellow;options=bold>SKIPPED</>'
×
UNCOV
271
                );
×
272
            }
273
        }
274

275
        return $content;
15✔
276
    }
277

278
    /**
279
     * Prompt the user for any missing arguments.
280
     *
281
     * @return void
282
     */
283
    protected function promptForMissingArguments(InputInterface $input, OutputInterface $output)
284
    {
285
        $install = null;
14✔
286

287
        if ($input->getOption('skip-install') === true) {
14✔
UNCOV
288
            $install = false;
×
289
        } elseif (\is_null($input->getOption('install'))) {
14✔
290
            $install = confirm('Run Workbench installation?', true);
1✔
291
        }
292

293
        if (! \is_null($install)) {
14✔
294
            $input->setOption('install', $install);
1✔
295
        }
296
    }
297

298
    /**
299
     * Get the console command options.
300
     *
301
     * @return array
302
     */
303
    protected function getOptions()
304
    {
305
        return [
15✔
306
            ['force', 'f', InputOption::VALUE_NONE, 'Overwrite any existing files'],
15✔
307
            ['install', null, InputOption::VALUE_NEGATABLE, 'Run Workbench installation'],
15✔
308
            ['basic', null, InputOption::VALUE_NONE, 'Workbench installation without discovers and routes'],
15✔
309

310
            /** @deprecated */
311
            ['skip-install', null, InputOption::VALUE_NONE, 'Skipped Workbench installation (deprecated)'],
15✔
312
        ];
15✔
313
    }
314
}
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