xp-framework / command
XPCLI
Installs: 58 594
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 3
Forks: 0
Open Issues: 1
Requires
- php: >=7.4.0
- xp-framework/core: ^12.0 | ^11.0 | ^10.15
- xp-framework/reflection: ^3.1
Requires (Dev)
- xp-framework/test: ^2.0 | ^1.0
README
Also known as "xpcli": Command line argument parsing via annotations.
Example
use util\cmd\{Command, Arg}; use rdbms\DriverManager; use io\streams\Streams; /** * Performs an SQL query */ class Query extends Command { private $connection, $query; private $verbose= false; /** Connection DSN, e.g. `mysql://user:pass@host[:port][/database]` */ #[Arg(position: 0)] public function useConnection(string $dsn) { $this->connection= DriverManager::getConnection($dsn); $this->connection->connect(); } /** SQL query. Use `-` to read from standard input */ #[Arg(position: 1)] public function useQuery(string $query) { if ('-' === $query) { $this->query= Streams::readAll($this->in->stream()); } else { $this->query= $query; } } /** Verbose output */ #[Arg] public function useVerbose() { $this->verbose= true; } /** @return int */ public function run() { $this->verbose && $this->out->writeLine('@ ', $this->connection); $this->verbose && $this->out->writeLine('>>> ', $this->query); $result= $this->connection->open($this->query); if ($result->isSuccess()) { $this->verbose && $this->out->writeLine('<<< ', $result->affected()); return $result->affected() ? 0 : 1; } else { $this->verbose && $this->out->writeLine('<<< Results'); foreach ($result as $found => $record) { $this->out->writeLine($record); } return isset($found) ? 0 : 2; } } }
To execute the class, use the cmd
command:
$ xp -m /path/to/rdbms cmd Query 'mysql://localhost/test' 'select * from account' -v @ rdbms.mysqlx.MySqlxConnection(->rdbms.DSN@(mysql://localhost/test), rdbms.mysqlx.MySqlxProtocol(...) >>> select * from account <<< Results [ account_id => 1 username => "kiesel" email => "alex.dandrea@example.com" ] [ account_id => 2 username => "thekid" email => "timm.friebe@example.com" ]
To show the command's usage, supply -?
or --help
: