### DataStore Interface Usage Example Source: https://github.com/acquia/cli/blob/main/_autodocs/06-interfaces-and-contracts.md Demonstrates how to use the DataStoreInterface with a concrete implementation like CloudDataStore. Shows setting, getting with dot notation, checking existence, and removing data. ```php $store = new CloudDataStore('~/.acli/cloud-datastore.json'); // Set $store->set('acli_key', 'uuid-12345'); // Get with dot notation $secret = $store->get('keys.uuid-12345.secret'); // Check existence if ($store->exists('acsf_factories.factory.acsitefactory.com')) { // ACSF factory configured } // Remove $store->remove('keys.uuid-12345'); ``` -------------------------------- ### Example JsonDataStore File Source: https://github.com/acquia/cli/blob/main/_autodocs/03-datastore-system.md This is an example of a JSON file used by the JsonDataStore. It stores generic configuration data. ```json { "acli_key": "uuid-123", "keys": { "uuid-123": { "secret": "secret-value" } } } ``` -------------------------------- ### Example: Prompting for Subscription Choice Source: https://github.com/acquia/cli/blob/main/_autodocs/04-command-system.md Demonstrates how to fetch subscriptions using the API client and then prompt the user to choose one. ```php $subscriptions = $this->cloudApiClientService->getClient()->request('get', '/subscriptions'); $subscription = $this->promptChooseFromObjectsOrArrays( $subscriptions, 'uuid', 'name', 'Select a subscription:' ); ``` -------------------------------- ### Get Cloud API Client and Fetch Applications Source: https://github.com/acquia/cli/blob/main/_autodocs/02-api-client-services.md Inject the ClientService to obtain the Cloud API client and fetch all applications. This example demonstrates making a basic API request to retrieve application data. ```php use AcquiaCloudApi\Endpoints\Applications; // In a command, inject ClientService public function execute(InputInterface $input, OutputInterface $output): int { // Get Cloud API client $cloudClient = $this->cloudApiClientService->getClient(); // Make API request $request = new Applications($cloudClient); $apps = $request->getAll(); foreach ($apps as $app) { $output->writeln($app->name); } return 0; } ``` -------------------------------- ### Spinner Usage Example Source: https://github.com/acquia/cli/blob/main/_autodocs/05-helpers-and-output.md Shows how to use the Spinner class directly for long-running operations, including starting, advancing, and finishing the spinner. ```php $spinner = new Spinner($output); $spinner->setMessage('Processing...'); $spinner->start(); while (!$done) { $spinner->advance(); // do work } $spinner->finish(); ``` -------------------------------- ### Clone and Install Acquia CLI Source: https://github.com/acquia/cli/blob/main/CONTRIBUTING.md Clone the Acquia CLI repository and install Composer dependencies to set up your local development environment. ```bash git clone git@github.com:acquia/cli.git cd cli composer install ./bin/acli ``` -------------------------------- ### Authenticate Using API Credentials Source: https://github.com/acquia/cli/blob/main/_autodocs/06-interfaces-and-contracts.md Example of how to authenticate by checking for the presence of API credentials. Throws an exception if credentials are not found. ```php // Injected in CommandBase public function authenticate(): void { if (!$this->credentials->getCloudKey() && !$this->credentials->getCloudSecret()) { throw new AcquiaCliException('Authentication failed: no credentials found'); } } ``` -------------------------------- ### Checklist Usage Example Source: https://github.com/acquia/cli/blob/main/_autodocs/05-helpers-and-output.md Demonstrates how to instantiate and use the Checklist class to add items, update progress, and mark items as complete. ```php $checklist = new Checklist($this->output); $checklist->addItem('Downloading files...'); // ... do work ... $checklist->updateProgressBar('Downloaded 50%'); $checklist->completePreviousItem(); $checklist->addItem('Processing files...'); // ... more work ... $checklist->completePreviousItem(); ``` -------------------------------- ### CommandBase Argument Helper Example Source: https://github.com/acquia/cli/blob/main/_autodocs/04-command-system.md Demonstrates how to use fluent methods like acceptApplicationUuid() and acceptEnvironmentId() to add standard arguments to a command's configuration. ```php protected function configure(): void { $this->setDescription('List environments') ->acceptApplicationUuid() ->acceptEnvironmentId(); } ``` -------------------------------- ### Execute Acquia CLI Command Source: https://github.com/acquia/cli/blob/main/_autodocs/07-environment-variables.md Example of running an Acquia CLI command after setting environment variables. ```bash # Run command acli api:get /applications ``` -------------------------------- ### Create an API Connector Instance Source: https://github.com/acquia/cli/blob/main/_autodocs/06-interfaces-and-contracts.md Example of creating an API connector using the `ConnectorFactory`. The type of connector returned depends on authentication methods and MEO status. ```php $factory = new ConnectorFactory( config: ['key' => 'mykey', 'secret' => 'mysecret'], baseUri: 'https://api.acquia.com/v1', accountsUri: 'https://accounts.acquia.com' ); $connector = $factory->createConnector(); // Returns Connector, AccessTokenConnector, or PathRewriteConnector // depending on auth method and MEO status ``` -------------------------------- ### Render and View RST Documentation on Mac Source: https://github.com/acquia/cli/blob/main/CONTRIBUTING.md After generating RST documentation, this command renders and opens it for viewing using `restview`. Ensure `restview` is installed via Homebrew. ```bash brew install restview ./bin/acli self:make-docs > /tmp/acli.rst && restview /tmp/acli.rst ``` -------------------------------- ### Binary Detection Methods Source: https://github.com/acquia/cli/blob/main/_autodocs/05-helpers-and-output.md Checks for the existence of commands in the system's PATH and validates that a list of required binaries are installed. Throws an exception if any required binary is missing. ```php public function commandExists(string $command): bool ``` ```php public function checkRequiredBinariesExist(array $binaries = []): void ``` ```php $this->localMachineHelper->checkRequiredBinariesExist(['git', 'php', 'drush']); // Throws AcquiaCliException if any binary not found ``` -------------------------------- ### Read Cloud API Key from Datastore Source: https://github.com/acquia/cli/blob/main/_autodocs/03-datastore-system.md Example of retrieving a cloud API key and its secret from the datastore. Assumes CloudDataStore is injected. ```php // In a command with CloudDataStore injected $key = $this->datastoreCloud->get('acli_key'); if ($key && $this->datastoreCloud->exists("keys.$key.secret")) { $secret = $this->datastoreCloud->get("keys.$key.secret"); } ``` -------------------------------- ### AcquiaCloudApi Response Object Example Source: https://github.com/acquia/cli/blob/main/_autodocs/06-interfaces-and-contracts.md Instantiate response objects from AcquiaCloudApi and access properties using object attributes or array keys. ```php $app = new ApplicationResponse(['uuid' => '12345', 'name' => 'myapp']); echo $app->uuid; // '12345' echo $app['name']; // 'myapp' ``` -------------------------------- ### RequireAuth Attribute Example Source: https://github.com/acquia/cli/blob/main/_autodocs/04-command-system.md Demonstrates how to use the #[RequireAuth] attribute to mark a command that requires Cloud Platform API authentication. The CommandBase class automatically adds help text for this requirement. ```php #[RequireAuth] class MyCommand extends CommandBase { } ``` -------------------------------- ### Registering an Event Listener Source: https://github.com/acquia/cli/blob/main/_autodocs/09-advanced-topics.md YAML configuration for registering a kernel event listener. This example shows how to tag a service as an event listener for the 'console.error' event, specifying the method to be called. ```yaml kernel.event_listener: event: console.error method: onConsoleError ``` -------------------------------- ### Get Environment by ID Source: https://github.com/acquia/cli/blob/main/_autodocs/04-command-system.md Retrieves an environment's details using its ID. Returns null if the environment is not found. ```php public function getEnvironmentFromId(string $environmentId): ?EnvironmentResponse ``` -------------------------------- ### DataStoreInterface Methods Source: https://github.com/acquia/cli/blob/main/_autodocs/03-datastore-system.md Provides the core interface for interacting with the DataStore system, allowing for setting, getting, removing, and checking the existence of key-value pairs. ```APIDOC ## DataStoreInterface **Namespace:** `Acquia\Cli\DataStore` ### Methods - **`set(string $key, mixed $value): void`** - **Description:** Set a key-value pair and persist to disk. - **Parameters:** - `key` (string): The key to set. Supports dot notation for nested values. - `value` (mixed): The value to associate with the key. - **Returns:** `void` - **`get(string $key): mixed`** - **Description:** Get value by key. Returns null if the key is not found. - **Parameters:** - `key` (string): The key to retrieve. Supports dot notation for nested values. - **Returns:** `mixed` - The value associated with the key, or null if not found. - **`remove(string $key): void`** - **Description:** Remove a key and persist changes. - **Parameters:** - `key` (string): The key to remove. Supports dot notation for nested values. - **Returns:** `void` - **`dump(): void`** - **Description:** Persist the current state of the datastore to disk. - **Parameters:** None - **Returns:** `void` - **`exists(string $key): bool`** - **Description:** Check if a key exists in the datastore. - **Parameters:** - `key` (string): The key to check for existence. Supports dot notation for nested values. - **Returns:** `bool` - True if the key exists, false otherwise. ### Dot Notation Keys can use dot notation for accessing nested data structures: - `credentials.cloud.key` will access the value at `credentials['cloud']['key']`. - `array.0` will access the first element of an array at index 0. ``` -------------------------------- ### Get Acquia Cloud API Client Source: https://github.com/acquia/cli/blob/main/_autodocs/08-quick-reference.md Obtain an instance of the Cloud API client service. Ensure the machine is authenticated before use. ```php // Injected in CommandBase $client = $this->cloudApiClientService->getClient(); // Check authentication if (!$this->cloudApiClientService->isMachineAuthenticated()) { throw new AcquiaCliException('Machine not authenticated'); } ``` -------------------------------- ### Output Verbosity Control in PHP Source: https://github.com/acquia/cli/blob/main/_autodocs/08-quick-reference.md Shows how to control output verbosity for messages based on command-line flags (-v, -vv, -vvv). Includes examples for writing messages at different verbosity levels and checking the current verbosity. ```php // Write only when verbose $this->output->writeln('Details...', OutputInterface::VERBOSITY_VERBOSE); // Write only when very verbose (-vv) $this->output->writeln('More details...', OutputInterface::VERBOSITY_VERY_VERBOSE); // Write only in debug mode (-vvv) $this->output->writeln('Debug details...', OutputInterface::VERBOSITY_DEBUG); // Check verbosity level if ($this->output->isVerbose()) { // show extra information } if ($this->output->isVeryVerbose()) { // show debug information } ``` -------------------------------- ### API Command Helper for Generating Commands Source: https://github.com/acquia/cli/blob/main/_autodocs/04-command-system.md Generates API commands by processing OpenAPI specifications. It loads the spec, parses endpoints, and creates command instances with parameters and examples. ```php output); $checklist->addItem('Downloading files...'); // ... do work ... $checklist->updateProgressBar('Downloaded 50%'); $checklist->completePreviousItem(); $checklist->addItem('Processing files...'); // ... do work ... $checklist->completePreviousItem(); ``` -------------------------------- ### CommandBase Initialization Method Source: https://github.com/acquia/cli/blob/main/_autodocs/04-command-system.md The initialize method in CommandBase handles the command lifecycle, including setting up I/O, telemetry prompts, authentication checks, and version updates. ```php protected function initialize(InputInterface $input, OutputInterface $output): void ``` -------------------------------- ### Get Symfony Console Progress Bar Helper Source: https://github.com/acquia/cli/blob/main/_autodocs/04-command-system.md Returns a configured Symfony Console ProgressBar helper instance for tracking progress. ```php protected function getProgressBar(int $steps, string $message = ''): ProgressBar ``` -------------------------------- ### Run Full Test Suite Source: https://github.com/acquia/cli/blob/main/_autodocs/00-index.md Execute the complete suite of tests for the Acquia CLI project. ```bash composer test ``` -------------------------------- ### Command Discovery in Kernel::build() Source: https://github.com/acquia/cli/blob/main/_autodocs/04-command-system.md Illustrates the process of auto-registering commands within the Kernel's build method. It iterates through container definitions, identifies Command instances, and adds them to the application, excluding abstract classes. ```php // In Kernel::build() foreach ($containerBuilder->getDefinitions() as $definition) { if (!is_a($definition->getClass(), Command::class, true)) { continue; } if ($definition->isAbstract()) { continue; // Skip abstract classes } $appDefinition->addMethodCall('add', [ new Reference($definition->getClass()), ]); } ``` -------------------------------- ### Get Cloud Application by UUID Source: https://github.com/acquia/cli/blob/main/_autodocs/04-command-system.md Fetches a specific Acquia Cloud application using its UUID. Handles caching and API errors. ```php public function getCloudApplication(string $applicationUuid): ApplicationResponse ``` -------------------------------- ### LocalMachineHelper Constructor Source: https://github.com/acquia/cli/blob/main/_autodocs/05-helpers-and-output.md Initializes the LocalMachineHelper with input, output, and logger dependencies. ```APIDOC ## LocalMachineHelper Constructor ### Description Initializes the LocalMachineHelper with input, output, and logger dependencies. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response None ``` -------------------------------- ### Configure Token Storage via Environment Variables Source: https://github.com/acquia/cli/blob/main/_autodocs/07-environment-variables.md Store access tokens and their expiry in separate files for enhanced security. Ensure the files are only readable by the user. ```bash # Secure token storage export ACLI_ACCESS_TOKEN_FILE="/secure/location/token.txt" export ACLI_ACCESS_TOKEN_EXPIRY_FILE="/secure/location/expiry.txt" # Ensure files are readable only by user chmod 600 /secure/location/token.txt chmod 600 /secure/location/expiry.txt ``` -------------------------------- ### Define Configuration Tree Source: https://github.com/acquia/cli/blob/main/_autodocs/09-advanced-topics.md Example of defining a configuration tree structure using Symfony's Config component. This is used to define the schema for CLI configuration. ```php public function getConfigTreeBuilder(): TreeBuilder { $treeBuilder = new TreeBuilder('cloud_data'); $rootNode = $treeBuilder->getRootNode(); $rootNode ->children() ->scalarNode('acli_key') ->info('Current API key UUID') ->end() ->arrayNode('keys') ->info('API keys mapping') ->variablePrototype()->end() ->end() ->booleanNode('send_telemetry') ->info('Whether to send telemetry') ->end() ->end(); return $treeBuilder; } ``` -------------------------------- ### IdeCommandTrait Source: https://github.com/acquia/cli/blob/main/_autodocs/05-helpers-and-output.md Provides helpers for commands that only work in Cloud IDE environments. ```APIDOC ## `IdeCommandTrait` ### Description Provides helpers for commands that only work in Cloud IDE environments. ### Methods - `isIde(): bool` Check if running in Cloud IDE (REMOTEIDE_UUID set). - `getIdeHelperText(): string` Standard help text for IDE-only commands. ``` -------------------------------- ### Generate RST Documentation Source: https://github.com/acquia/cli/blob/main/CONTRIBUTING.md Run this command to generate documentation for all Acquia CLI commands in RST format. ```bash ./bin/acli self:make-docs ``` -------------------------------- ### Creating a Progress Bar Source: https://github.com/acquia/cli/blob/main/_autodocs/08-quick-reference.md Visualize the progress of a long-running operation. Initialize with the total steps and a message, then advance for each completed step. ```php $progressBar = $this->getProgressBar(100, 'Processing items...'); for ($i = 0; $i < 100; $i++) { // Do work $progressBar->advance(); } $progressBar->finish(); ``` -------------------------------- ### Displaying a Table Source: https://github.com/acquia/cli/blob/main/_autodocs/08-quick-reference.md Use this to render tabular data in the console. Requires initializing a table object and adding rows before rendering. ```php $table = $this->getTable(['ID', 'Name', 'Status']); $table->addRow(['1', 'App 1', 'Active']); $table->addRow(['2', 'App 2', 'Inactive']); $table->render(); ``` -------------------------------- ### Prompt User to Choose Environment Source: https://github.com/acquia/cli/blob/main/_autodocs/04-command-system.md Prompts the user to select an environment for a given application from the Acquia Cloud API client. ```php protected function promptChooseEnvironment(Client $acquiaCloudClient, string $applicationUuid): object|array|null ``` -------------------------------- ### ACSF Factory Structure Example Source: https://github.com/acquia/cli/blob/main/_autodocs/03-datastore-system.md This JSON structure illustrates how ACSF factory configurations are stored within the CloudDataStore. It includes details about active users and their associated API keys. ```json { "acsf_factories": { "factory1.acsitefactory.com": { "active_user": "username1", "users": { "username1": { "username": "username1", "key": "api_key_value" } } } } } ``` -------------------------------- ### Build acli.phar Source: https://github.com/acquia/cli/blob/main/CONTRIBUTING.md Steps to build the acli.phar for testing changes in production mode. This process is similar to the CI workflow. ```bash composer install --no-dev --optimize-autoloader cp .env.example .env ./bin/acli ckc && ./bin/acli cc composer box-install composer box-compile ``` -------------------------------- ### Alias Cache Management Source: https://github.com/acquia/cli/blob/main/_autodocs/05-helpers-and-output.md A class for caching application and environment alias resolutions to enhance command performance. Provides methods to get, set, and clear cached alias values. ```php class AliasCache { public function get(string $key): ?string public function set(string $key, string $value): void public function clear(): void } ``` -------------------------------- ### Make acli.phar Executable Source: https://github.com/acquia/cli/blob/main/CONTRIBUTING.md After downloading the acli.phar artifact, make it executable using chmod. ```bash chmod +x acli.phar ``` -------------------------------- ### Build Acquia CLI PHAR Archive Source: https://github.com/acquia/cli/blob/main/_autodocs/09-advanced-topics.md These commands are used to compile the Acquia CLI into a standalone PHAR archive using Box. Ensure Box is installed via Composer before running the compile command. ```bash # Install Box composer box-install # Compile PHAR composer box-compile # Result: acli.phar ``` -------------------------------- ### Dump Entire Datastore Contents Source: https://github.com/acquia/cli/blob/main/_autodocs/03-datastore-system.md Prints the entire contents of the datastore to the output. Useful for debugging and inspection. ```php // Print entire datastore $this->datastoreCloud->dump(); ``` -------------------------------- ### WizardCommandBase Class Structure Source: https://github.com/acquia/cli/blob/main/_autodocs/04-command-system.md Defines the structure of the abstract WizardCommandBase class, which serves as a foundation for interactive wizard-style commands. It outlines methods for managing user questions. ```php abstract class WizardCommandBase extends CommandBase { protected function addQuestion(Question $question): void protected function getQuestion(string $name): mixed protected function setQuestion(string $name, mixed $value): void protected function askQuestion(string $name): mixed } ``` -------------------------------- ### Make Direct Acquia Cloud API Requests Source: https://github.com/acquia/cli/blob/main/_autodocs/08-quick-reference.md Perform direct HTTP requests (GET, POST, PATCH, DELETE) to Acquia Cloud API endpoints using the client. JSON bodies are supported for POST and PATCH requests. ```php // GET request $response = $client->request('GET', '/applications'); // POST with JSON body $response = $client->request('POST', '/applications', [ 'json' => [ 'name' => 'My App', 'type' => 'drupal8' ] ]); // PATCH request $response = $client->request('PATCH', "/applications/$uuid", [ 'json' => ['status' => 'active'] ]); // DELETE request $response = $client->request('DELETE', "/applications/$uuid"); ``` -------------------------------- ### IDE Environment Check Helper Source: https://github.com/acquia/cli/blob/main/_autodocs/05-helpers-and-output.md Offers methods to determine if the CLI is running within a Cloud IDE environment. Use `isIde` to check the environment and `getIdeHelperText` to retrieve standard help text for IDE-only commands. ```php trait IdeCommandTrait { protected function isIde(): bool public static function getIdeHelperText(): string } ``` -------------------------------- ### Store Configuration in Datastore Source: https://github.com/acquia/cli/blob/main/_autodocs/08-quick-reference.md Set configuration values in the datastore, supporting both top-level and nested keys using dot notation. The existence of a key can also be checked. ```php // Store a value $this->datastoreCloud->set('my_setting', 'value'); // Store nested value (dot notation) $this->datastoreCloud->set('nested.key.path', 'value'); // Check if exists if ($this->datastoreCloud->exists('key')) { // ... } // Remove key $this->datastoreCloud->remove('key'); ``` -------------------------------- ### Execute System Commands Safely Source: https://github.com/acquia/cli/blob/main/_autodocs/08-quick-reference.md Execute system commands using an array form for safety, or a string form for shell commands with pipes (use with caution). Requires `localMachineHelper`. ```php // Safe command execution with array form $process = $this->localMachineHelper->execute( ['git', 'clone', $repoUrl, $destination], null, // callback $workingDir, true // print output ); if (!$process->isSuccessful()) { throw new AcquiaCliException("Git clone failed: {$process->getErrorOutput()}"); } // Shell command with pipes (unsafe - use carefully) $process = $this->localMachineHelper->executeFromCmd( "cat file.txt | grep pattern | wc -l", null, $cwd, true ); ``` -------------------------------- ### Prompt User to Choose Application Source: https://github.com/acquia/cli/blob/main/_autodocs/04-command-system.md Prompts the user to select an application from a list provided by the Acquia Cloud API client. ```php protected function promptChooseApplication(Client $acquiaCloudClient): object|array|null ``` -------------------------------- ### Checkout Release Tag Locally Source: https://github.com/acquia/cli/blob/main/CONTRIBUTING.md Use this command to check out the specific tag for a release locally. Replace '[the tag]' with the actual tag name. ```bash git remote update git checkout [the tag] ``` -------------------------------- ### Logging Levels in PHP Source: https://github.com/acquia/cli/blob/main/_autodocs/08-quick-reference.md Demonstrates how to log messages at different verbosity levels (debug, info, warning, error) using the logger service. Contextual data can be passed with debug messages. ```php // Available in commands and helpers $this->logger->debug('Debug message', ['context' => 'data']); $this->logger->info('Info message'); $this->logger->warning('Warning message'); $this->logger->error('Error message'); ``` -------------------------------- ### Process Configuration Source: https://github.com/acquia/cli/blob/main/_autodocs/05-helpers-and-output.md Provides methods to check TTY status, debugging mode, and retrieve important directory paths. ```APIDOC ## Process Configuration ### Description Provides methods to check TTY status, debugging mode, and retrieve important directory paths. ### Methods - `isTty(): bool` - `isDebugging(): bool` - `getHomeDir(): static string` - User home directory (from HOME env or system) - `getConfigDir(): static string` - CLI config directory (`~/.acli` or ACLI_HOME) - `getProjectDir(): static string` - Project root directory (from pwd or ACLI_REPO_ROOT) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **isTty**: `bool` - True if the current terminal is a TTY. - **isDebugging**: `bool` - True if debugging is enabled. - **getHomeDir**: `string` - Path to the user's home directory. - **getConfigDir**: `string` - Path to the CLI configuration directory. - **getProjectDir**: `string` - Path to the project root directory. ``` -------------------------------- ### Copy RST Documentation to Clipboard Source: https://github.com/acquia/cli/blob/main/CONTRIBUTING.md This command generates RST documentation and pipes it directly to the clipboard for easy copying. ```bash ./bin/acli self:make-docs | pbcopy ``` -------------------------------- ### Acquia\Cli\CommandFactoryInterface Source: https://github.com/acquia/cli/blob/main/_autodocs/06-interfaces-and-contracts.md Factory pattern for creating command instances with dependency injection. ```APIDOC ## Interface: `Acquia\Cli\CommandFactoryInterface` ### Description Factory pattern for creating command instances with dependency injection. ### Methods - **`createCommand()`** - Returns: `ApiBaseCommand` - Description: Create API command instance (populated by ApiCommandHelper) - **`createListCommand()`** - Returns: `ApiListCommand|AcsfListCommand` - Description: Create list command for displaying endpoints ``` -------------------------------- ### Set Cloud API Credentials via Environment Variables Source: https://github.com/acquia/cli/blob/main/_autodocs/07-environment-variables.md Configure Cloud API access using a key and secret, or an access token and its expiry. Ensure these variables are exported before running CLI commands. ```bash # Cloud API with key/secret export ACLI_KEY="12345678-abcd-1234-abcd-123456789abc" export ACLI_SECRET="abcdef123456..." # Or use access token export ACLI_ACCESS_TOKEN="eyJ0eXAiOiJKV1QiLC..." export ACLI_ACCESS_TOKEN_EXPIRY="2025-06-24T12:00:00Z" ``` -------------------------------- ### Service Registration in Production Source: https://github.com/acquia/cli/blob/main/_autodocs/09-advanced-topics.md YAML configuration for defining services in a production environment. This includes default settings, individual service definitions with classes and arguments, aliased services, services defined by factories, and services with tags. ```yaml services: _defaults: autowire: true autoconfigure: true public: false # Single service definition MyService: class: Acquia\Cli\MyService arguments: - '@OtherService' - '%some.parameter%' # Aliased service MyAlias: alias: MyService # Service with factory MyFactory: factory: ['@FactoryClass', 'create'] # Service with tag MyCommand: class: Acquia\Cli\Command\MyCommand tags: - { name: 'kernel.event_listener', event: 'console.execute', method: 'onExecute' } ``` -------------------------------- ### Acquia\Cli\DataStore\DataStoreInterface Source: https://github.com/acquia/cli/blob/main/_autodocs/06-interfaces-and-contracts.md Contract for persistent key-value storage. ```APIDOC ## Interface: `Acquia\Cli\DataStore\DataStoreInterface` ### Description Contract for persistent key-value storage. ### Methods - **`set(string $key, mixed $value): void`** - Parameters: - `key` (string): The key for the value. - `value` (mixed): The value to store. - Returns: `void` - Description: Set key-value pair and persist. - **`get(string $key): mixed`** - Parameters: - `key` (string): The key to retrieve. - Returns: `mixed` - The value associated with the key, or null if missing. - Description: Retrieve value by key. - **`dump(): void`** - Returns: `void` - Description: Persist current data to disk. - **`remove(string $key): void`** - Parameters: - `key` (string): The key to remove. - Returns: `void` - Description: Remove key and persist. - **`exists(string $key): bool`** - Parameters: - `key` (string): The key to check for existence. - Returns: `bool` - True if the key exists, false otherwise. - Description: Check key existence. ### Dot Notation Keys support dot notation for nested access: - `credentials.cloud.key` → `credentials['cloud']['key']` - `array.0` → `array[0]` ### Example ```php $store = new CloudDataStore('~/.acli/cloud-datastore.json'); // Set $store->set('acli_key', 'uuid-12345'); // Get with dot notation $secret = $store->get('keys.uuid-12345.secret'); // Check existence if ($store->exists('acsf_factories.factory.acsitefactory.com')) { // ACSF factory configured } // Remove $store->remove('keys.uuid-12345'); ``` ``` -------------------------------- ### Telemetry Event Tracking with TelemetryHelper Source: https://github.com/acquia/cli/blob/main/_autodocs/05-helpers-and-output.md Manages telemetry event tracking via Amplitude for usage analytics. Initialize this helper to send usage data. ```php class TelemetryHelper { public function __construct( protected CloudDataStore $datastoreCloud, protected LocalMachineHelper $localMachineHelper, protected ApiCredentialsInterface $credentials ) public function initialize(): void public function sendEvent(string $event, array $properties = []): void } ``` -------------------------------- ### API Command Factory Implementation Source: https://github.com/acquia/cli/blob/main/_autodocs/04-command-system.md Implements the CommandFactoryInterface to create Cloud API command instances. It requires various helper services and datastores for its constructor. ```php localMachineHelper->checkRequiredBinariesExist(['git', 'php', 'drush']); // Throws AcquiaCliException if any binary not found ``` ### Response #### Success Response (200) - **commandExists**: `bool` - True if the command exists, false otherwise. - **checkRequiredBinariesExist**: `void` - No return value on success, throws exception on failure. ``` -------------------------------- ### Convert Application Alias to UUID Source: https://github.com/acquia/cli/blob/main/_autodocs/04-command-system.md Initializes command input by converting an application alias (e.g., 'myapp' or 'realm:myapp') to its corresponding UUID. ```php private function convertApplicationAliasToUuid(InputInterface $input): void ``` -------------------------------- ### Create a New Acquia CLI Command Source: https://github.com/acquia/cli/blob/main/_autodocs/08-quick-reference.md Define a new command by extending `CommandBase` and implementing `configure` and `execute` methods. Use attributes for authentication and naming. Requires `CommandBase`, `RequireAuth`, and `AsCommand`. ```php setDescription('My command description') ->acceptApplicationUuid() ->acceptEnvironmentId(); } protected function execute(InputInterface $input, OutputInterface $output): int { $appUuid = $input->getArgument('applicationUuid'); $client = $this->cloudApiClientService->getClient(); // Make API calls $app = $client->request('GET', "/applications/$appUuid"); // Output results $this->io->success('Command completed!'); return 0; } } ``` -------------------------------- ### DataStoreContract Constants Source: https://github.com/acquia/cli/blob/main/_autodocs/03-datastore-system.md Provides constants for standardized datastore keys, such as SEND_TELEMETRY. Useful for accessing known configuration values. ```php class DataStoreContract { public const SEND_TELEMETRY = 'send_telemetry'; // Additional constants for known keys } ``` -------------------------------- ### Acquia CLI PHAR Configuration with Box Source: https://github.com/acquia/cli/blob/main/_autodocs/09-advanced-topics.md The `box.json` file configures the Box tool for compiling the Acquia CLI into a self-contained PHAR archive. It specifies file permissions, included files and directories, and versioning. ```json { "chmod": "0755", "files": ["src/", "config/", "assets/"], "files-bin": ["bin/acli"], "directories": ["vendor"], "git-version": "git-commit" } ``` -------------------------------- ### Local Database Configuration Source: https://github.com/acquia/cli/blob/main/_autodocs/07-environment-variables.md These environment variables configure the connection to a local database. They are required by commands with the `#[RequireLocalDb]` attribute and can be set via environment variables or command options. ```bash # Example of setting environment variables (actual values may vary) export ACLI_DB_HOST="localhost" export ACLI_DB_NAME="drupal" export ACLI_DB_USER="drupal" export ACLI_DB_PASSWORD="drupal" ``` -------------------------------- ### SSH Command Execution Helpers Source: https://github.com/acquia/cli/blob/main/_autodocs/05-helpers-and-output.md Provides methods for executing commands over SSH. Use `sshExecuteCommand` to run a command on a remote host and `getSshHost` to retrieve the SSH host for a given environment ID. ```php trait SshCommandTrait { protected function sshExecuteCommand( string $host, array $cmd, ?callable $callback = null ): Process protected function getSshHost(string $environmentId): string } ``` -------------------------------- ### Command Execution Source: https://github.com/acquia/cli/blob/main/_autodocs/05-helpers-and-output.md Executes local system commands. `execute` uses an array for safe command execution, while `executeFromCmd` uses a string for shell commands. ```APIDOC ## Command Execution ### Description Executes local system commands. `execute` uses an array for safe command execution, while `executeFromCmd` uses a string for shell commands. ### Method `execute(array $cmd, ?callable $callback = null, ?string $cwd = null, ?bool $printOutput = true, ?float $timeout = null, ?array $env = null, bool $stdin = true): Process` `executeFromCmd(string $cmd, ?callable $callback = null, ?string $cwd = null, ?bool $printOutput = true, ?int $timeout = null, ?array $env = null): Process` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **cmd / $cmd** (array|string) - Command array (execute) or shell string (executeFromCmd) - **callback** (?callable) - Called with each line of output - **cwd** (?string) - Working directory override - **printOutput** (?bool) - Whether to print output to console (default: true) - **timeout** (?float|?int) - Process timeout in seconds - **env** (?array) - Environment variables to set - **stdin** (bool) - Whether process accepts stdin (execute only, default: true) ### Request Example ```php // Execute with array (safe) $process = $this->localMachineHelper->execute(['git', 'clone', $repoUrl]); // Execute with shell string (when pipes needed) $process = $this->localMachineHelper->executeFromCmd('cat file.txt | grep pattern'); // With callback $process = $this->localMachineHelper->execute( ['drush', 'cron'], function(string $type, string $data) { $this->output->write($data); } ); ``` ### Response #### Success Response (200) - **Process** (`Symfony\Component\Process\Process`) - instance ``` -------------------------------- ### SSH Key Management with SshHelper Source: https://github.com/acquia/cli/blob/main/_autodocs/05-helpers-and-output.md Manages SSH key generation, configuration, and validation. Use this class to interact with local SSH keys. ```php class SshHelper { public function __construct( private LocalMachineHelper $localMachineHelper, private LoggerInterface $logger, private string $sshDir ) public function getLocalPublicSshKey(): ?string public function setLocalPublicSshKey(string $publicKey): void public function deleteLocalPublicSshKey(): void public function createSshKey(string $filename, string $passphrase = ''): void } ```