### Installing getallheaders Polyfill for PHP < 5.6 using Composer Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/ralouphie/getallheaders/README.md This command installs a specific major version (version 2) of the `getallheaders` polyfill package using Composer, specifically for PHP environments older than version 5.6. This ensures compatibility with legacy PHP setups. ```Shell composer require ralouphie/getallheaders "^2" ``` -------------------------------- ### Installing Webmozart Assert with Composer (Bash) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/webmozart/assert/README.md This command demonstrates how to install the Webmozart Assert library using Composer, the dependency manager for PHP. Running this command adds the library to your project's dependencies. ```bash composer require webmozart/assert ``` -------------------------------- ### Installing MyOwnFreeHost API Client with Composer Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/infinityfree/mofh-client/README.md This snippet demonstrates how to install the MyOwnFreeHost API client library using Composer, the PHP dependency manager. It adds the `infinityfree/mofh-client` package to your project, making the API client available for use. ```bash composer require infinityfree/mofh-client ``` -------------------------------- ### Installing PSR Clock Interface Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/psr/clock/README.md This command installs the PSR Clock interface package using Composer, making it available for use in your PHP project. It's a required dependency for either consuming or implementing the `Psr\Clock\ClockInterface`. ```bash composer require psr/clock ``` -------------------------------- ### Installing Guzzle via Composer in Bash Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/README.md This command demonstrates the recommended way to install the Guzzle HTTP client using Composer, the PHP dependency manager. Running this command in your project's root directory will add `guzzlehttp/guzzle` to your `composer.json` and download the necessary files. ```bash composer require guzzlehttp/guzzle ``` -------------------------------- ### Defining Group API Operations in XML Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This XML snippet defines various API operations for managing groups, including listing, searching, creating, deleting, getting, and updating groups. It specifies HTTP methods, URIs, documentation, and parameters for each command, serving as a traditional service description. ```xml Get a list of groups Uses a search query to get a list of groups Create a group Delete a group by ID Update a group ``` -------------------------------- ### Installing getallheaders Polyfill for PHP 5.6+ using Composer Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/ralouphie/getallheaders/README.md This command installs the `getallheaders` polyfill package using Composer for PHP environments version 5.6 and above. It ensures the latest compatible version of the polyfill is added to your project's dependencies. ```Shell composer require ralouphie/getallheaders ``` -------------------------------- ### Installing Stella-Maris Clock Package with Composer Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/stella-maris/clock/README.md This command installs the `stella-maris/clock` package using Composer, the PHP dependency manager. It adds the clock interface implementation to your project's dependencies, making it available for use. ```bash composer require stella-maris/clock ``` -------------------------------- ### Updating Guzzle Command Options for Request Configuration Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This PHP example illustrates the deprecated and new approaches for configuring request-specific options on a Guzzle command. Previously, options like `command.headers` and `command.response_body` were set directly on the command; now, these should be nested under `command.request_options` using standard request options like `headers` and `save_as`. ```php $command = $client->getCommand('foo', array( 'command.headers' => array('Test' => '123'), 'command.response_body' => '/path/to/file' )); ``` ```php $command = $client->getCommand('foo', array( 'command.request_options' => array( 'headers' => array('Test' => '123'), 'save_as' => '/path/to/file' ) )); ``` -------------------------------- ### Installing Guzzle PSR-7 Package via Composer Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/psr7/README.md This snippet shows how to install the Guzzle PSR-7 package using Composer, the dependency manager for PHP. This command adds the package to your project's `composer.json` and downloads it. ```Shell composer require guzzlehttp/psr7 ``` -------------------------------- ### Installing PSR Log Interface with Composer (Bash) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/psr/log/README.md This snippet demonstrates the command-line instruction to install the `psr/log` package using Composer. This action adds the PSR-3 Logger Interface as a dependency to your PHP project, making it available for use or implementation. ```bash composer require psr/log ``` -------------------------------- ### Creating and Managing MyOwnFreeHost Accounts with PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/infinityfree/mofh-client/README.md This PHP example illustrates how to initialize the MyOwnFreeHost API client, create a new hosting account, and handle the API response. It shows how to set API credentials, define account parameters, send the request, and check for success or failure. ```php use \InfinityFree\MofhClient\Client; // Create a new API client with your API credentials. $client = Client::create([ 'apiUsername' => 'your_api_username', 'apiPassword' => 'your_api_password', 'plan' => 'my_plan', // Optional, you can define it here or define it with the createAccount call. ]); // Create a request object to create the request. $request = $client->createAccount([ 'username' => 'abcdefgh', // A unique, 8 character identifier of the account. 'password' => 'password123', // A password to login to the control panel, FTP and databases. 'domain' => 'userdomain.example.com', // Can be a subdomain or a custom domain. 'email' => 'user@example.com', // The email address of the user. 'plan' => 'my_plan', // Optional, you can submit a hosting plan here or with the Client instantiation. ]); // Send the API request and keep the response. $response = $request->send(); // Check whether the request was successful. if ($response->isSuccessful()) { echo 'You can login as: ' . $response->getVpUsername(); } else { echo 'Failed to create account: ' . $response->getMessage(); } ``` -------------------------------- ### Installing Guzzle Promises via Composer Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/promises/README.md This snippet demonstrates how to install the Guzzle Promises library using Composer, the PHP dependency manager. It adds `guzzlehttp/promises` to your project's dependencies, making the promise functionality available for use. ```shell composer require guzzlehttp/promises ``` -------------------------------- ### Initializing ExponentialBackoffPlugin (Before) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This snippet demonstrates the initialization of `Guzzle\Http\Plugin\ExponentialBackoffPlugin` before its refactoring. It shows how to create an instance with a maximum number of retries and custom failure codes, then add it as a subscriber to a Guzzle client. ```php use Guzzle\Http\Plugin\ExponentialBackoffPlugin; $backoffPlugin = new ExponentialBackoffPlugin($maxRetries, array_merge( ExponentialBackoffPlugin::getDefaultFailureCodes(), array(429) )); $client->addSubscriber($backoffPlugin); ``` -------------------------------- ### Configuring Redirects in Guzzle (PHP) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This code illustrates how to configure redirects using the `allow_redirects` request option in Guzzle, replacing the deprecated `configureRedirects()` method. It shows examples for standard redirects with a default maximum of 5, and strict redirects with a custom maximum. ```PHP // Standard redirects with a default of a max of 5 redirects $request = $client->createRequest('GET', '/', ['allow_redirects' => true]); ``` ```PHP // Strict redirects with a custom number of redirects $request = $client->createRequest('GET', '/', [ 'allow_redirects' => ['max' => 5, 'strict' => true] ]); ``` -------------------------------- ### Initializing Guzzle Client with Inspector (Before) - PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This snippet demonstrates the previous method of initializing a Guzzle client using `Guzzle\Service\Inspector::fromConfig` to process configuration, set defaults, and validate required parameters. It shows how the client was configured before the recommended change. ```php use Guzzle\Service\Inspector; class YourClient extends \Guzzle\Service\Client { public static function factory($config = array()) { $default = array(); $required = array('base_url', 'username', 'api_key'); $config = Inspector::fromConfig($config, $default, $required); $client = new self( $config->get('base_url'), $config->get('username'), $config->get('api_key') ); $client->setConfig($config); $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json')); return $client; } ``` -------------------------------- ### Accessing Commands in Guzzle ServiceDescription (Before) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This snippet demonstrates how to interact with commands using `Guzzle\Service\Description\ServiceDescription` before the API change. It shows methods for retrieving, checking existence, and adding `ApiCommandInterface` objects. ```php use Guzzle\Service\Description\ServiceDescription; $sd = new ServiceDescription(); $sd->getCommands(); // @returns ApiCommandInterface[] $sd->hasCommand($name); $sd->getCommand($name); // @returns ApiCommandInterface|null $sd->addCommand($command); // @param ApiCommandInterface $command ``` -------------------------------- ### Sending HTTP Requests with Guzzle Client (3.x vs 4.x) - PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This snippet illustrates the change in Guzzle's client methods like `get()` between versions 3.x and 4.x. In 3.x, these methods returned a request object which then needed to be explicitly sent. In 4.x, they directly send the request and return the response. It also shows how to achieve the 3.x behavior in 4.x by manually creating and sending a request. ```php // 3.0 $request = $client->get('/'); $response = $request->send(); // 4.0 $response = $client->get('/'); // or, to mirror the previous behavior $request = $client->createRequest('GET', '/'); $response = $client->send($request); ``` -------------------------------- ### Initializing Guzzle Client with Collection (After) - PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This snippet illustrates the updated method for initializing a Guzzle client, now using `Guzzle\Common\Collection::fromConfig`. This change promotes better dependency management and aligns with current Guzzle practices for handling client configuration, offering the same functionality with a different class. ```php use Guzzle\Common\Collection; class YourClient extends \Guzzle\Service\Client { public static function factory($config = array()) { $default = array(); $required = array('base_url', 'username', 'api_key'); $config = Collection::fromConfig($config, $default, $required); $client = new self( $config->get('base_url'), $config->get('username'), $config->get('api_key') ); $client->setConfig($config); $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json')); return $client; } ``` -------------------------------- ### Issuing Let's Encrypt Certificates with AcmeCore PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/infinityfree/acmecore/README.md This snippet demonstrates the complete process of obtaining a Let's Encrypt certificate using the AcmeCore PHP library. It covers initializing the secure HTTP client, requesting a certificate order, completing authorization challenges (e.g., DNS or HTTP), preparing the Certificate Signing Request (CSR), finalizing the order, and retrieving the issued certificate. The example uses sleep loops for waiting, but notes that custom scheduling can be implemented. ```PHP $secureHttpClientFactory = new SecureHttpClientFactory( new GuzzleHttpClient(), new Base64SafeEncoder(), new KeyParser(), new DataSigner(), new ServerErrorHandler() ); // $accountKeyPair instance of KeyPair $secureHttpClient = $secureHttpClientFactory->createSecureHttpClient($accountKeyPair); // Important, change to production LE directory for real certs! $acmeClient = new AcmeClient($secureHttpClient, 'https://acme-staging-v02.api.letsencrypt.org/directory'); // Request a certificate for mydomain.com. $certificateOrder = $acmeClient->requestOrder('mydomain.com'); // Retrieve the challenges to complete for mydomain.com. $challenges = $certificateOrder->getAuthorizationChallenges('mydomain.com'); // Now complete the challenge for the domain. // Find the challenge object for the verification type you want to do, e.g. http-01, dns-01. $challenge = $challenges[0]; // Ask the CA to confirm the authorization. $challenge = $acmeClient->challengeAuthorization($dnsChallenge); // Wait for the CA to complete the authorization. // This example uses a sleep loop, but you can schedule your own. while ($challenge->getStatus() != 'ready') { sleep(1); $challenge = $acmeClient->reloadAuthorization($challenge); } // Prepare the CSR $dn = new DistinguishedName('mydomain.com'); $keyPairGenerator = new KeyPairGenerator(); // Make a new key pair. We'll keep the private key as our cert key $domainKeyPair = $keyPairGenerator->generateKeyPair(); // This is the private key echo $domainKeyPair->getPrivateKey()->getPem()); // Generate CSR $csr = new CertificateRequest($dn, $domainKeyPair); // Tell the CA to generate the certificate. $certificateOrder = $acmeClient->finalizeOrder($certificateOrder, $csr); // Wait for the CA to complete the issuance. // This example uses a sleep loop, but you can schedule your own. while ($certificateOrder->getStatus() != 'issued') { sleep(1); $certificateOrder = $acmeClient->reloadOrder($certificateOrder->getOrderEndpoint()); } // Retrieve the generated certificate. $certificate = $acmeClient->retrieveCertificate($certificateOrder); // This is the generated certificate. echo $certificate->getPem(); ``` -------------------------------- ### Accessing Operations in Guzzle ServiceDescription (After) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This snippet illustrates the updated API for `Guzzle\Service\Description\ServiceDescription`, where 'commands' have been renamed to 'operations'. It shows the new methods for retrieving, checking existence, and adding `OperationInterface` objects. ```php use Guzzle\Service\Description\ServiceDescription; $sd = new ServiceDescription(); $sd->getOperations(); // @returns OperationInterface[] $sd->hasOperation($name); $sd->getOperation($name); // @returns OperationInterface|null $sd->addOperation($operation); // @param OperationInterface $operation ``` -------------------------------- ### Creating a GuzzleHttp Promise with Wait and Cancel Functions (PHP) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/promises/README.md Demonstrates how to create a `GuzzleHttp\Promise\Promise` object, providing an optional `$waitFn` to resolve the promise and a `$cancelFn` to handle cancellation. The example then asserts the promise's resolution value by synchronously waiting on it. ```PHP use GuzzleHttp\Promise\Promise; $promise = new Promise( function () use (&$promise) { $promise->resolve('waited'); }, function () { // do something that will cancel the promise computation (e.g., close // a socket, cancel a database query, etc...) } ); assert('waited' === $promise->wait()); ``` -------------------------------- ### Managing POST Request Bodies in Guzzle 4.x - PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This example demonstrates how to add fields and files to a POST request body in Guzzle 4.x. Unlike Guzzle 3.x where these methods were directly on the request object, Guzzle 4.x requires accessing the request's body via `getBody()` and then using methods like `setField()` and `addFile()` from the `PostBodyInterface`. ```php $request = $client->createRequest('POST', '/'); $request->getBody()->setField('foo', 'bar'); $request->getBody()->addFile(new PostFile('file_key', fopen('/path/to/content', 'r'))); ``` -------------------------------- ### Limiting Stream Size and Offset with LimitStream in PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/psr7/README.md Demonstrates using `GuzzleHttp\Psr7\LimitStream` to create a view of a subset of an existing stream. It allows specifying a maximum size and an offset from which to start reading, useful for chunking large files. ```PHP use GuzzleHttp\Psr7; $original = Psr7\Utils::streamFor(fopen('/tmp/test.txt', 'r+')); echo $original->getSize(); // >>> 1048576 // Limit the size of the body to 1024 bytes and start reading from byte 2048 $stream = new Psr7\LimitStream($original, 1024, 2048); echo $stream->getSize(); // >>> 1024 echo $stream->tell(); // >>> 0 ``` -------------------------------- ### Initializing BackoffPlugin with Factory Method (After) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This snippet illustrates the updated way to initialize the backoff plugin, now `Guzzle\Plugin\Backoff\BackoffPlugin`. It shows using a convenient factory method, `getExponentialBackoff`, and merging custom failure codes with `HttpBackoffStrategy` defaults, then adding it as a subscriber. ```php use Guzzle\Plugin\Backoff\BackoffPlugin; use Guzzle\Plugin\Backoff\HttpBackoffStrategy; // Use convenient factory method instead -- see implementation for ideas of what // you can do with chaining backoff strategies $backoffPlugin = BackoffPlugin::getExponentialBackoff($maxRetries, array_merge( HttpBackoffStrategy::getDefaultFailureCodes(), array(429) )); $client->addSubscriber($backoffPlugin); ``` -------------------------------- ### Migrating Event Subscriber Management in Guzzle PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This example demonstrates the change in managing event subscribers between Guzzle 3.x and 4.x. In Guzzle 3.x, `getEventDispatcher()` and `addSubscriber()`/`removeSubscriber()` were used. Guzzle 4.x replaces this with `getEmitter()` and `attach()`/`detach()` methods, reflecting the shift from Symfony's EventDispatcher to Guzzle's custom Emitter. ```PHP $mock = new Mock(); // 3.x $request->getEventDispatcher()->addSubscriber($mock); $request->getEventDispatcher()->removeSubscriber($mock); // 4.x $request->getEmitter()->attach($mock); $request->getEmitter()->detach($mock); ``` -------------------------------- ### Configuring LogPlugin with ClosureLogAdapter (Before) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This snippet demonstrates how to configure `Guzzle\Http\Plugin\LogPlugin` using `Guzzle\Common\Log\ClosureLogAdapter` before the namespace and parameter changes. It shows adding a subscriber to a Guzzle HTTP client with a specified log verbosity level. ```php use Guzzle\Common\Log\ClosureLogAdapter; use Guzzle\Http\Plugin\LogPlugin; /** @var \Guzzle\Http\Client */ $client; // $verbosity is an integer indicating desired message verbosity level $client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $verbosity = LogPlugin::LOG_VERBOSE);) ``` -------------------------------- ### Sending HTTP Requests with Guzzle in PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/README.md This snippet demonstrates how to send both synchronous and asynchronous HTTP requests using the Guzzle HTTP client in PHP. It shows how to initialize a client, make a GET request, retrieve the status code, headers, and response body, and handle asynchronous responses using promises. It requires the `guzzlehttp/guzzle` package. ```php $client = new \GuzzleHttp\Client(); $response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle'); echo $response->getStatusCode(); // 200 echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8' echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}' // Send an asynchronous request. $request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org'); $promise = $client->sendAsync($request)->then(function ($response) { echo 'I completed! ' . $response->getBody(); }); $promise->wait(); ``` -------------------------------- ### Setting Multiple Default Headers using Guzzle setDefaultOption (PHP) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This snippet demonstrates setting multiple default headers using `setDefaultOption()` by passing an associative array of header key-value pairs. This method applies the entire array to the 'headers' option. ```PHP $client->setDefaultOption('headers', array('header_name' => 'value')) ``` -------------------------------- ### Retrieving Default Headers using Guzzle Config (PHP) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md After the removal of `getDefaultHeaders()`, this snippet shows how to retrieve all default headers configured for the client. It uses `getConfig()->getPath()` to access the `request.options/headers` path, returning an array of headers. ```PHP $client->getConfig()->getPath('request.options/headers') ``` -------------------------------- ### Forwarding Rejection by Returning RejectedPromise in GuzzleHttp Promise (PHP) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/promises/README.md This example illustrates how to explicitly forward a rejection down the promise chain by returning a `GuzzleHttp\Promise\RejectedPromise` from an `$onRejected` callback. The subsequent `$onRejected` callback receives the original rejection reason. ```php use GuzzleHttp\Promise\Promise; use GuzzleHttp\Promise\RejectedPromise; $promise = new Promise(); $promise->then(null, function ($reason) { return new RejectedPromise($reason); })->then(null, function ($reason) { assert($reason === 'Error!'); }); $promise->reject('Error!'); ``` -------------------------------- ### Implementing Assertions in a PHP Class Constructor (PHP) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/webmozart/assert/README.md This PHP example shows how to use Webmozart Assert within a class constructor to validate input parameters. It asserts that the `$id` is an integer and greater than zero, throwing an `InvalidArgumentException` if validation fails. ```php use Webmozart\Assert\Assert; class Employee { public function __construct($id) { Assert::integer($id, 'The employee ID must be an integer. Got: %s'); Assert::greaterThan($id, 0, 'The employee ID must be a positive integer. Got: %s'); } } ``` -------------------------------- ### Checking Network-Path URI Reference in Guzzle PSR-7 (PHP) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/psr7/README.md Identifies if the URI is a network-path reference, which is a relative reference starting with two slash characters. This is useful for parsing and validating URI structures. ```PHP public static function isNetworkPathReference(UriInterface $uri): bool ``` -------------------------------- ### Configuring LogPlugin with MessageFormatter (After) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This snippet shows the updated configuration for `Guzzle\Plugin\Log\LogPlugin` and `Guzzle\Log` namespaces. It demonstrates using `Guzzle\Log\MessageFormatter` to specify the log message format when adding a `LogPlugin` subscriber to a Guzzle HTTP client. ```php use Guzzle\Log\ClosureLogAdapter; use Guzzle\Log\MessageFormatter; use Guzzle\Plugin\Log\LogPlugin; /** @var \Guzzle\Http\Client */ $client; // $format is a string indicating desired message format -- @see MessageFormatter $client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $format = MessageFormatter::DEBUG_FORMAT);) ``` -------------------------------- ### Handling Exceptions During Synchronous Wait in GuzzleHttp Promise (PHP) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/promises/README.md This example illustrates that if an exception is thrown within the promise's wait function during a `wait()` call, the promise is rejected with that exception, and the exception is re-thrown by the `wait()` method itself. ```php $promise = new Promise(function () use (&$promise) { throw new Exception('foo'); }); $promise->wait(); // throws the exception. ``` -------------------------------- ### Setting Multiple Default Headers using Guzzle Config (PHP) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This snippet shows how to set multiple default headers by providing an associative array to the client's configuration. It targets the `request.options/headers` path and assigns an array of header key-value pairs. ```PHP $client->getConfig()->setPath('request.options/headers', array('header_name' => 'value')) ``` -------------------------------- ### Creating Streams with GuzzleHttp\Psr7\Utils::streamFor (PHP) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/psr7/README.md This method creates a `StreamInterface` object from various input types like strings, resources, iterators, or callables. It's a versatile utility for stream instantiation. The examples demonstrate creating streams from a string, a file resource, and a generator function. ```php $stream = GuzzleHttp\Psr7\Utils::streamFor('foo'); $stream = GuzzleHttp\Psr7\Utils::streamFor(fopen('/path/to/file', 'r')); $generator = function ($bytes) { for ($i = 0; $i < $bytes; $i++) { yield ' '; } }; $stream = GuzzleHttp\Psr7\Utils::streamFor($generator(100)); ``` -------------------------------- ### Resolving a Guzzle Promise and Chaining in PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/promises/README.md This PHP example demonstrates how to resolve a `GuzzleHttp\Promise\Promise` using the `resolve()` method, triggering its `$onFulfilled` callbacks. It also shows promise chaining, where the return value of one `then()` callback is passed as the input to the subsequent `then()` callback in the chain, allowing for sequential asynchronous operations. ```php use GuzzleHttp\Promise\Promise; $promise = new Promise(); $promise ->then(function ($value) { // Return a value and don't break the chain return "Hello, " . $value; }) // This then is executed after the first then and receives the value // returned from the first then. ->then(function ($value) { echo $value; }); // Resolving the promise triggers the $onFulfilled callbacks and outputs // "Hello, reader." $promise->resolve('reader.'); ``` -------------------------------- ### Waiting on Already Rejected Promise in GuzzleHttp Promise (PHP) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/promises/README.md This example demonstrates that calling `wait()` on a promise that has already been rejected will result in an exception being thrown. If the rejection reason is an `\Exception`, it's thrown directly; otherwise, a `GuzzleHttp\Promise\RejectionException` is thrown. ```php $promise = new Promise(); $promise->reject('foo'); $promise->wait(); ``` -------------------------------- ### Rejecting a Guzzle Promise in PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/promises/README.md This PHP example demonstrates how to reject a `GuzzleHttp\Promise\Promise` using the `reject()` method. When a promise is rejected, the `$onRejected` callback, if provided to the `then()` method, is invoked with the specified rejection reason. This handles error conditions in asynchronous operations. ```php use GuzzleHttp\Promise\Promise; $promise = new Promise(); $promise->then(null, function ($reason) { echo $reason; }); $promise->reject('Error!'); // Outputs "Error!" ``` -------------------------------- ### Enabling Deprecation Warnings in Guzzle Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This PHP snippet demonstrates how to enable `E_USER_DEPRECATED` warnings in Guzzle to identify usage of deprecated methods. Setting `\Guzzle\Common\Version::$emitWarnings` to `true` will cause Guzzle to emit warnings when deprecated APIs are used, aiding in migration. ```php \Guzzle\Common\Version::$emitWarnings = true; ``` -------------------------------- ### Setting Single Default Header using Guzzle setDefaultOption (PHP) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md As an alternative to `getConfig()->setPath()`, this snippet illustrates setting a single default header using `setDefaultOption()`. It directly targets a specific header name within the 'headers' option path. ```PHP $client->setDefaultOption('headers/{header_name}', 'value') ``` -------------------------------- ### Using ClockInterface for DateTime Comparison in PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/stella-maris/clock/README.md This PHP example demonstrates how to inject and use the `ClockInterface` within a class to check if a given `DateTimeImmutable` object is in the past. The `now()` method of the injected clock provides the current time for comparison, ensuring testability and consistent time handling. ```php use StellaMaris/Clock/CLockInterface; final class PastChecker { public function __construct(private ClockInterface $clock) {} public function hasDateTimeAlreadyPassed(DateTimeImmutable $item): bool { return $item < $this->clock->now(); } } ``` -------------------------------- ### Using Psr\Clock\ClockInterface in PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/psr/clock/README.md This PHP example demonstrates how to inject and use the `Psr\Clock\ClockInterface` within a class. The `now()` method is called on the injected clock instance to retrieve the current date and time as a `DateTimeImmutable` object, allowing for time-dependent operations. ```php clock = $clock; } public function doSomething() { /** @var DateTimeImmutable $currentDateAndTime */ $currentDateAndTime = $this->clock->now(); // do something useful with that information } } ``` -------------------------------- ### Defining Group API Operations in JSON Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This JSON snippet represents the transformed API service description, detailing operations for groups. It specifies HTTP methods, URIs, summaries, and parameters for each operation, mirroring the functionality defined in the XML but in a more modern, machine-readable format. ```json { "name": "Zendesk REST API v2", "apiVersion": "2012-12-31", "description":"Provides access to Zendesk views, groups, tickets, ticket fields, and users", "operations": { "list_groups": { "httpMethod":"GET", "uri": "groups.json", "summary": "Get a list of groups" }, "search_groups":{ "httpMethod":"GET", "uri": "search.json?query=\"{query} type:group\"", "summary": "Uses a search query to get a list of groups", "parameters":{ "query":{ "location": "uri", "description":"Zendesk Search Query", "type": "string", "required": true } } }, "create_group": { "httpMethod":"POST", "uri": "groups.json", "summary": "Create a group", "parameters":{ "data": { "type": "array", "location": "body", "description":"Group JSON", "filters": "json_encode", "required": true }, "Content-Type":{ "type": "string", "location":"header", "static": "application/json" } } }, "delete_group": { "httpMethod":"DELETE", "uri": "groups/{id}.json", "summary": "Delete a group", "parameters":{ "id":{ "location": "uri", "description":"Group to delete by ID", "type": "integer", "required": true } } }, "get_group": { "httpMethod":"GET", "uri": "groups/{id}.json", "summary": "Get a ticket", "parameters":{ "id":{ "location": "uri", "description":"Group to get by ID", "type": "integer", "required": true } } }, "update_group": { "httpMethod":"PUT", "uri": "groups/{id}.json", "summary": "Update a group", "parameters":{ "id": { "location": "uri", "description":"Group to update by ID", "type": "integer", "required": true }, "data": { "type": "array", "location": "body", "description":"Group JSON", "filters": "json_encode", "required": true }, "Content-Type":{ "type": "string", "location":"header", "static": "application/json" } } } } } ``` -------------------------------- ### Getting Array of Header Values in PSR-7 in PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/psr/http-message/docs/PSR7-Usage.md Demonstrates how to retrieve all values for a given header as an array of strings using `getHeader` on both `RequestInterface` and `ResponseInterface` objects. Each element in the array represents a distinct value for the header. ```php // getting value from request headers $request->getHeader('Content-Type'); // will return: ["text/html", "charset=UTF-8"] // getting value from response headers $response->getHeader('My-Custom-Header'); // will return: ["My Custom Message", "The second message"] ``` -------------------------------- ### Getting Comma-Separated Header Values in PSR-7 in PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/psr/http-message/docs/PSR7-Usage.md Explains how to retrieve all values for a given header as a single comma-separated string using `getHeaderLine` on both `RequestInterface` and `ResponseInterface` objects. This is useful for headers that can have multiple values. ```php // getting value from request headers $request->getHeaderLine('Content-Type'); // will return: "text/html; charset=UTF-8" // getting value from response headers $response->getHeaderLine('My-Custom-Header'); // will return: "My Custom Message; The second message" ``` -------------------------------- ### Handling Streaming Responses in Guzzle (PHP) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This snippet demonstrates the evolution of handling streaming responses in Guzzle. In Guzzle 3.0, `PhpStreamRequestFactory` was used to create a stream from a request. In Guzzle 4.0, streaming is enabled via the `stream` request option, returning a `ResponseInterface` with a body stream that can be directly read. ```PHP // 3.0 use Guzzle\Stream\PhpStreamRequestFactory; $request = $client->get('/'); $factory = new PhpStreamRequestFactory(); $stream = $factory->fromRequest($request); $data = $stream->read(1024); ``` ```PHP // 4.0 $response = $client->get('/', ['stream' => true]); // Read some data off of the stream in the response body $data = $response->getBody()->read(1024); ``` -------------------------------- ### Resolving a Promise as a Deferred in PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/promises/README.md This example demonstrates that in GuzzleHttp Promises, the Promise object itself acts as the deferred value. This design allows direct resolution of the promise using the resolve() method, delivering a value to its attached handlers without needing a separate deferred object. ```php $promise = new Promise(); $promise->then(function ($value) { echo $value; }); // The promise is the deferred value, so you can deliver a value to it. $promise->resolve('foo'); // prints "foo" ``` -------------------------------- ### Setting Single Default Header using Guzzle Config (PHP) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md After the removal of `setDefaultHeaders()`, this snippet demonstrates how to set a single default header for requests using the client's configuration. It specifies a path to the header name within `request.options/headers` and assigns a value. ```PHP $client->getConfig()->setPath('request.options/headers/{header_name}', 'value') ``` -------------------------------- ### Configuring Global CurlMulti Reuse in Guzzle PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This snippet demonstrates how to re-enable global reuse of the CurlMulti object across Guzzle clients. By listening to the `service_builder.create_client` event, a custom CurlMulti instance can be injected into each client as it is created, preventing plugin pollution issues that arise from the default behavior in Guzzle 3.2 and later. This requires a `Guzzle\Service\Builder\ServiceBuilder` instance and a `Guzzle\Http\Curl\CurlMulti` object. ```PHP $multi = new Guzzle\Http\Curl\CurlMulti(); $builder = Guzzle\Service\Builder\ServiceBuilder::factory('/path/to/config.json'); $builder->addListener('service_builder.create_client', function ($event) use ($multi) { $event['client']->setCurlMulti($multi); } }); ``` -------------------------------- ### Adding Event Listeners in Guzzle PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This snippet illustrates the updated method for adding event listeners in Guzzle. Guzzle 3.x used `getEventDispatcher()->addListener()`, while Guzzle 4.x transitions to `getEmitter()->on()`, aligning with the new event emitter architecture. The callback signature also changes slightly. ```PHP // 3.x $request->getEventDispatcher()->addListener('foo', function (Event $event) { /* ... */ } ); // 4.x $request->getEmitter()->on('foo', function (Event $event, $name) { /* ... */ } ); ``` -------------------------------- ### Modifying Request with Event System (Guzzle v5, PHP) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This snippet illustrates how to intercept and modify an HTTP request before it is sent using Guzzle v5's event system. It attaches a listener to the 'before' event, which allows direct mutation of the request object to add a custom header. This approach relies on the mutability of HTTP messages. ```php use GuzzleHttp\Event\BeforeEvent; $client = new GuzzleHttp\Client(); // Get the emitter and listen to the before event. $client->getEmitter()->on('before', function (BeforeEvent $e) { // Guzzle v5 events relied on mutation $e->getRequest()->setHeader('X-Foo', 'Bar'); }); ``` -------------------------------- ### Prefixing Native PHP Function Calls in Guzzle Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This code snippet demonstrates the change in Guzzle's internal native function calls. To prevent method overloading by other libraries, all calls to native PHP functions (like curl_version()) are now explicitly prefixed with a backslash, ensuring the global function is invoked. This is a crucial change for compatibility and predictability. ```php // Before: curl_version(); ``` ```php // After: \curl_version(); ``` -------------------------------- ### Modifying Request with Middleware (Guzzle v6, PHP) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/guzzle/UPGRADING.md This snippet shows the Guzzle v6 approach to modifying an HTTP request using a middleware stack. It creates a handler stack, pushes a 'mapRequest' middleware that returns a new immutable request object with an added header, and then injects this handler into the Guzzle client. This method aligns with PSR-7's immutable message design. ```php use GuzzleHttp\Middleware; // Create a handler stack that has all of the default middlewares attached $handler = GuzzleHttp\HandlerStack::create(); // Push the handler onto the handler stack $handler->push(Middleware::mapRequest(function (RequestInterface $request) { // Notice that we have to return a request object return $request->withHeader('X-Foo', 'Bar'); })); // Inject the handler into the client $client = new GuzzleHttp\Client(['handler' => $handler]); ``` -------------------------------- ### Initializing CKEditor 5 Classic Editor in JavaScript Source: https://github.com/mahtab2003/xera/blob/dev/assets/default/ckeditor/index.html This snippet initializes the CKEditor 5 Classic Editor on an HTML element identified by '#editor'. It demonstrates how to create an editor instance, optionally configure its toolbar (though commented out here), and handle successful creation or log any errors that occur during the process. The created editor instance is then made globally accessible via `window.editor`. ```JavaScript ClassicEditor .create( document.querySelector( '#editor' ), { // toolbar: [ 'heading', '|', 'bold', 'italic', 'link' ] } ) .then( editor => { window.editor = editor; } ) .catch( err => { console.error( err.stack ); } ); ``` -------------------------------- ### Running the GuzzleHttp Global Task Queue (PHP) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/promises/README.md Demonstrates how to access and manually run the global task queue instance provided by `GuzzleHttp\Promise\Utils::queue()`. This is essential for ensuring that promises are resolved when operating asynchronously in an event-driven environment. ```PHP // Get the global task queue $queue = GuzzleHttp\Promise\Utils::queue(); $queue->run(); ``` -------------------------------- ### Demonstrating Webmozart Assert Exception Handling (PHP) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/webmozart/assert/README.md This snippet illustrates the exceptions thrown by the `Employee` class constructor when invalid IDs are provided. It shows how `Webmozart\Assert\InvalidArgumentException` is raised with specific messages for type and value validation failures. ```php new Employee('foobar'); // => Webmozart\Assert\InvalidArgumentException: // The employee ID must be an integer. Got: string new Employee(-10); // => Webmozart\Assert\InvalidArgumentException: // The employee ID must be a positive integer. Got: -10 ``` -------------------------------- ### Customizing Error Messages with Webmozart Assert (PHP) Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/webmozart/assert/README.md This snippet demonstrates how to provide a custom error message when using Webmozart Assert. The `%s` placeholder is consistently used for the tested value, allowing for clear and customizable exception messages. ```php Assert::string($path, 'The path is expected to be a string. Got: %s'); ``` -------------------------------- ### Using PSR Log LoggerInterface in PHP Class Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/psr/log/README.md This PHP class `Foo` illustrates how to integrate and conditionally use the `Psr\Log\LoggerInterface` for logging within an application. It shows dependency injection of the logger and its usage for logging informational messages and capturing exceptions with error logs. ```php logger = $logger; } public function doSomething() { if ($this->logger) { $this->logger->info('Doing work'); } try { $this->doSomethingElse(); } catch (Exception $exception) { $this->logger->error('Oh no!', array('exception' => $exception)); } // do something useful } } ``` -------------------------------- ### Understanding Prepending to PSR-7 Stream Body in PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/psr/http-message/docs/PSR7-Usage.md Explains the behavior of prepending content to a PSR-7 stream, which is not a direct operation like appending. It demonstrates that writing to a stream after seeking to the beginning will overwrite existing content from that point, rather than inserting it. ```php // assuming our response is initially empty $body = $repsonse->getBody(); // writing the string "abcd" $body->write('abcd'); // seeking to start of stream $body->seek(0); // writing 'ef' $body->write('ef'); // at this point the stream contains "efcd" ``` -------------------------------- ### Lazily Opening Files with LazyOpenStream in PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/psr7/README.md Shows how `GuzzleHttp\Psr7\LazyOpenStream` defers opening a file until an actual I/O operation (like reading or writing) is performed on the stream. This optimizes resource usage by only opening files when necessary. ```PHP use GuzzleHttp\Psr7; $stream = new Psr7\LazyOpenStream('/path/to/file', 'r'); // The file has not yet been opened... echo $stream->read(10); // The file is opened and read from only when needed. ``` -------------------------------- ### Declaring PSR Clock Implementation in composer.json Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/psr/clock/README.md This JSON snippet shows how to add `psr/clock-implementation` to the `provides` section of your `composer.json` file. This is crucial when your package implements the `Psr\Clock\ClockInterface`, signaling to Composer that your package fulfills this specific interface requirement. ```json { "provides": { "psr/clock-implementation": "1.0" } } ``` -------------------------------- ### Initializing BufferStream with High Water Mark in PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/psr7/README.md Illustrates the creation of a `GuzzleHttp\Psr7\BufferStream` with a specified high water mark. This stream buffers data and signals when its buffer exceeds a certain size, indicating that writers should pause. ```PHP use GuzzleHttp\Psr7; // When more than 1024 bytes are in the buffer, it will begin returning // false to writes. This is an indication that writers should slow down. $buffer = new Psr7\BufferStream(1024); ``` -------------------------------- ### Relativizing Target URI from Base URI - GuzzleHttp PSR-7 PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/psr7/README.md This static method calculates a relative URI reference from a given base URI to a target URI. It's the inverse of the `resolve()` method, useful for generating smaller, self-contained links within documents. It takes two `UriInterface` objects as input and returns a new `UriInterface` representing the relative path. ```PHP (string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target)) ``` ```PHP $base = new Uri('http://example.com/a/b/'); echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'. echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'. echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'. echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'. ``` -------------------------------- ### Decorating Stream Functions with FnStream in PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/psr7/README.md Illustrates how `GuzzleHttp\Psr7\FnStream` can be used to decorate an existing stream by overriding specific methods with custom functions. This allows for flexible extension or testing without concrete classes. ```PHP use GuzzleHttp\Psr7; $stream = Psr7\Utils::streamFor('hi'); $fnStream = Psr7\FnStream::decorate($stream, [ 'rewind' => function () use ($stream) { echo 'About to rewind - '; $stream->rewind(); echo 'rewound!'; } ]); $fnStream->rewind(); // Outputs: About to rewind - rewound! ``` -------------------------------- ### Normalizing URI with Configurable Flags - GuzzleHttp PSR-7 PHP Source: https://github.com/mahtab2003/xera/blob/dev/app/vendor/guzzlehttp/psr7/README.md This static method returns a normalized URI based on specified flags, which are a bitmask of normalizations to apply. It extends the default PSR-7 normalizations (lowercase scheme and host) with options like capitalizing percent-encoding, decoding unreserved characters, converting empty paths, and removing default host/port. The `$flags` parameter allows fine-grained control over the normalization process, including options for removing dot segments, duplicate slashes, and sorting query parameters. ```PHP public static function normalize(UriInterface $uri, $flags = self::PRESERVING_NORMALIZATIONS): UriInterface ```