Skip to content

Commit 932c308

Browse files
authored
More detailed Single File Application example
The original example didn't work because it didn't return the integer value. I expanded the example to something that's marginally useful (and more real-world).
1 parent 577b39f commit 932c308

File tree

1 file changed

+24
-9
lines changed

1 file changed

+24
-9
lines changed

components/console/single_command_tool.rst

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,25 +6,40 @@ In such a case, having to pass the command name each time is tedious. Fortunatel
66
it is possible to remove this need by declaring a single command application::
77

88
#!/usr/bin/env php
9-
<?php
10-
require __DIR__.'/vendor/autoload.php';
11-
9+
<?php // bin/file-counter.php
10+
require __DIR__.'/../vendor/autoload.php';
11+
1212
use Symfony\Component\Console\Input\InputArgument;
1313
use Symfony\Component\Console\Input\InputInterface;
14-
use Symfony\Component\Console\Input\InputOption;
1514
use Symfony\Component\Console\Output\OutputInterface;
1615
use Symfony\Component\Console\SingleCommandApplication;
17-
16+
1817
(new SingleCommandApplication())
19-
->setName('My Super Command') // Optional
18+
->setName('File Counter') // Optional
2019
->setVersion('1.0.0') // Optional
21-
->addArgument('foo', InputArgument::OPTIONAL, 'The directory')
22-
->addOption('bar', null, InputOption::VALUE_REQUIRED)
20+
->addArgument('dir', InputArgument::OPTIONAL, 'The directory', default: '.')
21+
->addOption('all', 'a', InputOption::VALUE_NONE, 'count all files')
2322
->setCode(function (InputInterface $input, OutputInterface $output): int {
24-
// output arguments and options
23+
$dir = realpath($input->getArgument('dir'));
24+
$all = $input->getOption('all');
25+
$finder = (new Symfony\Component\Finder\Finder())
26+
->in($dir)
27+
->files()
28+
->ignoreVCSIgnored(!$all)
29+
;
30+
$count = iterator_count($finder);
31+
$output->writeln( "$dir has $count " .
32+
($all ? "files" : "files in source control"));
33+
return SingleCommandApplication::SUCCESS;
2534
})
2635
->run();
2736

37+
Now run it with
38+
39+
php bin/file-counter.php
40+
41+
php bin/file-counter.php --all
42+
2843
You can still register a command as usual::
2944

3045
#!/usr/bin/env php

0 commit comments

Comments
 (0)