### Guzzle v5 Event-Based Middleware Example (PHP) Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/guzzle/UPGRADING.md Demonstrates how to use the event system in Guzzle v5 to listen for and modify requests before they are sent. This approach relied on 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'); }); ``` -------------------------------- ### Installing Guzzle HTTP Client using Composer in PHP Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/guzzle/README.md Provides the Composer command to install the Guzzle HTTP client library for PHP projects. This is the recommended method for managing Guzzle dependencies. ```bash composer require guzzlehttp/guzzle ``` -------------------------------- ### Update Request Options for Streaming Responses Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/guzzle/UPGRADING.md This example shows how to update the way streaming responses are handled when creating a command. The deprecated 'command.response_body' option is replaced with the 'command.request_options' array containing the 'save_as' key. ```php getCommand('foo', array( 'command.headers' => array('Test' => '123'), 'command.response_body' => '/path/to/file' )); // Updated usage: $command = $client->getCommand('foo', array( 'command.request_options' => array( 'headers' => array('Test' => '123'), 'save_as' => '/path/to/file' ) )); ?> ``` -------------------------------- ### Guzzle v6 Functional Middleware Example (PHP) Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/guzzle/UPGRADING.md Illustrates the functional middleware approach in Guzzle v6, which is compatible with immutable PSR-7 messages. This example shows how to modify a request by returning a new request object. ```php use GuzzleHttp\Middleware; use Psr\Http\Message\RequestInterface; // 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]); ``` -------------------------------- ### Install GuzzleHttp/psr7 via Composer Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/psr7/README.md This command installs the GuzzleHttp/psr7 package using Composer, the dependency manager for PHP. Ensure Composer is installed and accessible in your system's PATH. ```shell composer require guzzlehttp/psr7 ``` -------------------------------- ### Making Synchronous and Asynchronous HTTP Requests with Guzzle in PHP Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/guzzle/README.md Demonstrates how to use the Guzzle HTTP client in PHP to send both synchronous and asynchronous requests. It shows how to instantiate the client, make a GET request, retrieve response details (status code, headers, body), and handle asynchronous responses using promises. ```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(); ``` -------------------------------- ### Getting Domain Information Source: https://context7.com/pirsch-analytics/pirsch-php-sdk/llms.txt Retrieve the domain configuration associated with your API credentials. This information includes the domain ID and hostname, which are often needed for subsequent API calls. ```APIDOC ## Getting Domain Information ### Description Retrieve the domain configuration associated with your API credentials. ### Method GET ### Endpoint /v1/domain ### Parameters None ### Request Example ```php domain(); echo "Domain ID: " . $domain->id . "\n"; echo "Domain Name: " . $domain->hostname . "\n"; // Use $domain->id for subsequent filter queries } catch (Exception $e) { error_log('Failed to get domain: ' . $e->getMessage()); } ?> ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the domain. - **hostname** (string) - The hostname of the domain. - **tracking_code_id** (string) - The ID associated with the tracking code. - **created_at** (string) - The date and time when the domain was created. #### Response Example ```json { "id": "your-domain-id", "hostname": "example.com", "tracking_code_id": "your-tracking-code-id", "created_at": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Track Page Views with Custom Options using pageview() Source: https://context7.com/pirsch-analytics/pirsch-php-sdk/llms.txt Tracks a page view using custom options defined in the HitOptions class, allowing overrides for URL, IP, user agent, and more. Requires session to be started, Pirsch\Client, and Pirsch\HitOptions. Handles exceptions during tracking. ```php url = 'https://example.com/custom-page'; $options->ip = '192.168.1.1'; $options->user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0'; $options->accept_language = 'en-US,en;q=0.9'; $options->title = 'My Custom Page Title'; $options->referrer = 'https://google.com'; $options->screen_width = 1920; $options->screen_height = 1080; $options->tags = ['category' => 'blog', 'author' => 'john']; // Client hint headers (optional, for enhanced device detection) $options->sec_ch_ua = '"Chromium";v="120", "Google Chrome";v="120"'; $options->sec_ch_ua_mobile = '?0'; $options->sec_ch_ua_platform = '"Windows"'; try { $result = $client->pageview($options); echo "Page view tracked successfully"; } catch (Exception $e) { error_log('Error: ' . $e->getMessage()); } ``` -------------------------------- ### Integrate Guzzle Promises with React Event Loop Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/promises/README.md Shows an example of integrating Guzzle promises with the React event loop using a periodic timer to ensure the task queue is run on each tick, allowing promises to resolve asynchronously. ```php $loop = React\EventLoop\Factory::create(); $loop->addPeriodicTimer(0, [$queue, 'run']); ``` -------------------------------- ### Handling POST Body with Files and Fields (PHP) Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/guzzle/UPGRADING.md Demonstrates how to set POST fields and add files to a request body using the `GuzzleHttpPostPostBodyInterface`. This replaces the older methods on the request object and requires using the body's methods directly. ```php $request = $client->createRequest('POST', '/'); $request->getBody()->setField('foo', 'bar'); $request->getBody()->addFile(new PostFile('file_key', fopen('/path/to/content', 'r'))); ``` -------------------------------- ### Get and Replace PSR-7 Message Body Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/psr/http-message/docs/PSR7-Usage.md Illustrates how to get the message body stream from a PSR-7 response, perform operations on it, and then replace the response's body. This approach is recommended for clarity and preventing errors. ```php $body = $response->getBody(); // operations on body, eg. read, write, seek // ... // replacing the old body $response->withBody($body); // this last statement is optional as we working with objects // in this case the "new" body is same with the "old" one // the $body variable has the same value as the one in $request, only the reference is passed ``` -------------------------------- ### Create and Manage a Guzzle Promise Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/promises/README.md Demonstrates the creation of a Guzzle Promise with optional wait and cancel functions, and how to resolve it. It also shows how to use the wait() method to synchronously retrieve the promise's value. ```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()); ``` -------------------------------- ### Client Request Handling (PHP) Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/guzzle/UPGRADING.md Demonstrates the evolution of making requests with the Pirsch PHP SDK client from version 3.0 to 4.0. Version 4.0 simplifies request sending by directly returning the response, while also offering a way to maintain the previous behavior of creating and then sending requests. ```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); ``` -------------------------------- ### Convert HTTP Message to String with GuzzleHttpPsr7Message::toString Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/psr7/README.md Demonstrates the use of GuzzleHttp\Psr7\Message::toString() to get the string representation of an HTTP message. This is useful for debugging or logging. ```php $request = new GuzzleHttp\Psr7\Request('GET', 'http://example.com'); echo GuzzleHttp\Psr7\Message::toString($request); ``` -------------------------------- ### Handling Streaming Responses in Guzzle Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/guzzle/UPGRADING.md Demonstrates how to create and read from streaming responses in Guzzle, comparing the older 3.0 approach with the current 4.0 method. The 4.0 version simplifies streaming by directly returning a ResponseInterface with a body stream. ```php // 3.0 use GuzzleStreamPhpStreamRequestFactory; $request = $client->get('/'); $factory = new PhpStreamRequestFactory(); $stream = $factory->fromRequest($request); $data = $stream->read(1024); // 4.0 $response = $client->get('/', ['stream' => true]); // Read some data off of the stream in the response body $data = $response->getBody()->read(1024); ``` -------------------------------- ### Check if a URI is an absolute-path reference Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/psr7/README.md Checks if a Psr\Http\Message\UriInterface is an absolute-path reference. These references start with a single forward slash, indicating an absolute path from the root, e.g., '/path'. ```PHP use GuzzleHttp\Psr7\Uri; use Psr\Http\Message\UriInterface; // Assuming $uri is an instance of UriInterface $isAbsolutePath = Uri::isAbsolutePathReference($uri); ``` -------------------------------- ### PSR-7 Interfaces Overview Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/psr/http-message/docs/PSR7-Interfaces.md An overview of the core PSR-7 interfaces and their descriptions. ```APIDOC ## PSR-7 Interfaces The following interfaces are defined in PSR-7 for handling HTTP messages: ### Interfaces - **`Psr\Http\Message\MessageInterface`**: Representation of a HTTP message. - **`Psr\Http\Message\RequestInterface`**: Representation of an outgoing, client-side request. - **`Psr\Http\Message\ServerRequestInterface`**: Representation of an incoming, server-side HTTP request. - **`Psr\Http\Message\ResponseInterface`**: Representation of an outgoing, server-side response. - **`Psr\Http\Message\StreamInterface`**: Describes a data stream. - **`Psr\Http\Message\UriInterface`**: Value object representing a URI. - **`Psr\Http\Message\UploadedFileInterface`**: Value object representing a file uploaded through an HTTP request. ``` -------------------------------- ### Read a subset of an existing stream using LimitStream Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/psr7/README.md Demonstrates LimitStream for reading a specific portion of an existing stream. This is useful for segmenting large files, for example, for multipart uploads. ```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 ``` -------------------------------- ### Guzzle Logging Plugin: Namespace and Configuration Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/guzzle/UPGRADING.md Illustrates the migration of Guzzle's logging functionality, including namespace changes for LogPlugin and ClosureLogAdapter, and updates to message formatting. The verbosity level is replaced by a message format string. ```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)); ``` ```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)); ``` -------------------------------- ### Implement a Custom Stream Decorator with GuzzleHttpPsr7StreamDecoratorTrait Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/psr7/README.md Shows how to create a custom stream decorator by utilizing the GuzzleHttp\Psr7\StreamDecoratorTrait. This example implements an EofCallbackStream that executes a callback function when the end of the stream is reached. ```php use Psr\Http\Message\StreamInterface; use GuzzleHttp\Psr7\StreamDecoratorTrait; class EofCallbackStream implements StreamInterface { use StreamDecoratorTrait; private $callback; private $stream; public function __construct(StreamInterface $stream, callable $cb) { $this->stream = $stream; $this->callback = $cb; } public function read($length) { $result = $this->stream->read($length); // Invoke the callback when EOF is hit. if ($this->eof()) { ($this->callback)(); } return $result; } } use GuzzleHttp\Psr7; $original = Psr7\Utils::streamFor('foo'); $eofStream = new EofCallbackStream($original, function () { echo 'EOF!'; }); $eofStream->read(2); $eofStream->read(1); // echoes "EOF!" $eofStream->seek(0); $eofStream->read(3); // echoes "EOF!" ``` -------------------------------- ### Get Message Body Summary with GuzzleHttpPsr7Message::bodySummary Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/psr7/README.md Shows how to use GuzzleHttp\Psr7\Message::bodySummary() to retrieve a concise summary of an HTTP message's body. The summary can be truncated to a specified length. ```php $request = new GuzzleHttp\Psr7\Request('GET', 'http://example.com', [], 'This is a test body.'); $summary = GuzzleHttp\Psr7\Message::bodySummary($request, 20); var_dump($summary); ``` -------------------------------- ### Implementing Stream Decorators with StreamDecoratorTrait Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/psr7/README.md Demonstrates how to create custom stream decorators using the StreamDecoratorTrait. ```APIDOC ## Implementing stream decorators ### Description Creating a stream decorator is very easy thanks to the `GuzzleHttp\Psr7\StreamDecoratorTrait`. This trait provides methods that implement `Psr\Http\Message\StreamInterface` by proxying to an underlying stream. Just `use` the `StreamDecoratorTrait` and implement your custom methods. ### Example: EofCallbackStream This decorator calls a specific function when the last byte is read from a stream. ```php use Psr\Http\Message\StreamInterface; use GuzzleHttp\Psr7\StreamDecoratorTrait; class EofCallbackStream implements StreamInterface { use StreamDecoratorTrait; private $callback; private $stream; public function __construct(StreamInterface $stream, callable $cb) { $this->stream = $stream; $this->callback = $cb; } public function read($length) { $result = $this->stream->read($length); // Invoke the callback when EOF is hit. if ($this->eof()) { ($this->callback)(); } return $result; } } // Usage: use GuzzleHttp\Psr7; $original = Psr7\Utils::streamFor('foo'); $eofStream = new EofCallbackStream($original, function () { echo 'EOF!'; }); $eofStream->read(2); $eofStream->read(1); // echoes "EOF!" $eofStream->seek(0); $eofStream->read(3); // echoes "EOF!" ``` ``` -------------------------------- ### Setting Default User Agent and SSL Verification (PHP) Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/guzzle/UPGRADING.md Illustrates how to configure default request options for User-Agent and SSL verification in GuzzleHttp, replacing the removed `setUserAgent()` and `setSslVerification()` methods. This approach utilizes the client's configuration to set these options. ```php $client->setConfig('defaults/headers/User-Agent', 'Foo/Bar ' . $client::getDefaultUserAgent()); $client->setConfig('defaults/verify', true); ``` -------------------------------- ### Get Domain Information with PHP Source: https://context7.com/pirsch-analytics/pirsch-php-sdk/llms.txt Retrieves the domain configuration linked to your API credentials. This function requires the Pirsch SDK client and returns domain details like ID and hostname. ```php domain(); echo "Domain ID: " . $domain->id . "\n"; echo "Domain Name: " . $domain->hostname . "\n"; // Use $domain->id for subsequent filter queries } catch (Exception $e) { error_log('Failed to get domain: ' . $e->getMessage()); } ``` -------------------------------- ### Migrating Event Listener Attachment in Guzzle PHP Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/guzzle/UPGRADING.md Demonstrates how to migrate from Guzzle 3.x's addSubscriber/removeSubscriber methods using EventDispatcher to Guzzle 4.x's attach/detach methods using Emitter. This change simplifies event handling and improves performance. ```php $mock = new Mock(); // 3.x $request->getEventDispatcher()->addSubscriber($mock); $request->getEventDispatcher()->removeSubscriber($mock); // 4.x $request->getEmitter()->attach($mock); $request->getEmitter()->detach($mock); ``` -------------------------------- ### Get Comma-Separated Header Value (PSR-7) Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/psr/http-message/docs/PSR7-Usage.md Explains how to retrieve the value of a header as a single, comma-separated string from both PSR-7 request and response objects. Useful for headers like 'Content-Type'. ```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" ``` -------------------------------- ### Initialize Pirsch PHP Client Source: https://context7.com/pirsch-analytics/pirsch-php-sdk/llms.txt Initializes the Pirsch client using either OAuth client credentials or a single access token. Supports custom timeouts and base URLs. Requires the 'vendor/autoload.php' file and the Pirsch\Client class. ```php getBody(); $body->rewind(); // or $body->seek(0); $bodyText = $body->getContents(); ``` -------------------------------- ### Get Header Values as Array (PSR-7) Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/psr/http-message/docs/PSR7-Usage.md Demonstrates retrieving header values as an array from PSR-7 request and response objects. This method is useful when a header might have multiple distinct values. ```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"] ``` -------------------------------- ### Determine Mimetype from Filename using GuzzleHttpPsr7MimeType::fromFilename (PHP) Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/psr7/README.md The fromFilename method determines the MIME type of a file based on its file extension. It provides a convenient way to get the content type for a given file. ```php $mimetype = GuzzleHttp\Psr7\MimeType::fromFilename('document.pdf'); ``` -------------------------------- ### Guzzle ServiceDescription: Commands to Operations Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/guzzle/UPGRADING.md Demonstrates the refactoring of Guzzle's ServiceDescription from using 'Commands' to 'Operations'. This change affects how API commands are accessed and managed within the SDK. ```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 ``` ```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 ``` -------------------------------- ### PHP: Registering Callbacks with a Promise Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/promises/README.md Demonstrates how to register fulfillment and rejection callbacks for a Guzzle Promise. The `then` method accepts two optional arguments: a callback for fulfillment and a callback for rejection. ```php use GuzzleHttp\Promise\Promise; $promise = new Promise(); $promise->then( // $onFulfilled function ($value) { echo 'The promise was fulfilled.'; }, // $onRejected function ($reason) { echo 'The promise was rejected.'; } ); ``` -------------------------------- ### Use GuzzleHttpPsr7StreamWrapper to Get PHP Stream Resources Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/psr7/README.md Illustrates how to obtain a standard PHP stream resource from a PSR-7 stream using GuzzleHttp\Psr7\StreamWrapper::getResource(). This allows compatibility with PHP functions that expect stream resources. ```php use GuzzleHttp\Psr7\StreamWrapper; $stream = GuzzleHttp\Psr7\Utils::streamFor('hello!'); $resource = StreamWrapper::getResource($stream); echo fread($resource, 6); // outputs hello! ``` -------------------------------- ### Retrieving Visitor Statistics Source: https://context7.com/pirsch-analytics/pirsch-php-sdk/llms.txt Get visitor counts and session data over time using the Pirsch client and a configured filter. This includes total visitors, page views, sessions, bounce rate, and time-series data. ```APIDOC ## Retrieving Visitor Statistics ### Description Get visitor counts and session data over time. This endpoint allows fetching various metrics like total visitors, page views, sessions, bounce rate, and real-time active visitors. ### Method POST (for most statistics endpoints, as they typically use a filter object) ### Endpoint - `/v1/visitors/total` (for `totalVisitors`) - `/v1/visitors` (for `visitors`) - `/v1/visitors/active` (for `activeVisitors`) - `/v1/growth` (for `growth`) ### Parameters #### Request Body (Filter Object) See the documentation for "Creating Filters for Statistics" for a detailed list of filter parameters. ### Request Example ```php domain(); $filter = new Filter(); $filter->id = $domain->id; $filter->from = date('Y-m-d', strtotime('-30 days')); $filter->to = date('Y-m-d'); $filter->scale = 'day'; try { // Total visitors summary $total = $client->totalVisitors($filter); echo "Total Visitors: " . $total->visitors . "\n"; echo "Total Page Views: " . $total->views . "\n"; echo "Total Sessions: " . $total->sessions . "\n"; echo "Bounce Rate: " . $total->bounces . "%\n"; // Visitors over time (array of daily data) $visitors = $client->visitors($filter); foreach ($visitors as $day) { echo $day->day . ": " . $day->visitors . " visitors\n"; } // Active visitors (real-time) $active = $client->activeVisitors($filter); echo "Currently Active: " . $active->visitors . "\n"; // Growth rates compared to previous period $growth = $client->growth($filter); echo "Visitor Growth: " . $growth->visitors_growth . "%\n"; } catch (Exception $e) { error_log('Statistics error: ' . $e->getMessage()); } ?> ``` ### Response #### Success Response (200) - **totalVisitors**: - **visitors** (integer) - Total number of unique visitors. - **views** (integer) - Total number of page views. - **sessions** (integer) - Total number of sessions. - **bounces** (float) - Bounce rate percentage. - **visitors**: An array of objects, where each object represents a time period (based on the `scale` in the filter) and contains: - **day** (string) - The date/time of the period. - **visitors** (integer) - The number of visitors during that period. - **views** (integer) - The number of page views during that period. - **sessions** (integer) - The number of sessions during that period. - **activeVisitors**: - **visitors** (integer) - The number of currently active visitors. - **growth**: - **visitors_growth** (float) - The percentage growth in visitors compared to the previous period. - **views_growth** (float) - The percentage growth in page views compared to the previous period. - **sessions_growth** (float) - The percentage growth in sessions compared to the previous period. #### Response Example (for `totalVisitors`) ```json { "visitors": 1500, "views": 3000, "sessions": 2000, "bounces": 45.5 } ``` #### Response Example (for `visitors` with scale 'day') ```json [ { "day": "2024-01-01", "visitors": 50, "views": 100, "sessions": 70 }, { "day": "2024-01-02", "visitors": 55, "views": 110, "sessions": 75 } ] ``` ``` -------------------------------- ### GuzzleHttp Client Constructor Changes (PHP) Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/guzzle/UPGRADING.md Shows how the GuzzleHttp client constructor has been updated to accept an associative array for configuration. This includes setting a base URL, default request options, and custom adapters or message factories. ```php // Example of new constructor usage $client = new GuzzleHttpClient([ 'base_url' => 'http://example.com', 'defaults' => [ 'headers' => ['X-Foo' => 'Bar'] ], 'adapter' => new CustomAdapter(), 'message_factory' => new CustomMessageFactory() ]); ``` -------------------------------- ### Track Conversion Goals and Funnels with Pirsch PHP SDK Source: https://context7.com/pirsch-analytics/pirsch-php-sdk/llms.txt Shows how to retrieve conversion goal statistics and analyze funnel performance using the Pirsch PHP SDK. This involves initializing the client and using a Filter object to specify the date range and domain, then calling specific methods for goals and funnels. ```php domain(); $filter = new Filter(); $filter->id = $domain->id; $filter->from = date('Y-m-d', strtotime('-30 days')); $filter->to = date('Y-m-d'); try { // Conversion goals (configured in Pirsch dashboard) $goals = $client->conversionGoals($filter); echo "Conversion Goals:\n"; foreach ($goals as $goal) { echo " " . $goal->name . ": " . $goal->visitors . " conversions\n"; } // List all funnels $funnels = $client->listFunnel($filter); echo "\nFunnels:\n"; foreach ($funnels as $funnel) { echo " - " . $funnel->name . " (ID: " . $funnel->id . ")\n"; // Get funnel statistics $filter->funnel_id = $funnel->id; $funnelData = $client->funnel($filter); foreach ($funnelData as $step) { echo " Step " . $step->step . ": " . $step->visitors . " visitors\n"; } } } catch (Exception $e) { error_log('Conversion statistics error: ' . $e->getMessage()); } ``` -------------------------------- ### Parse HTTP Message String with GuzzleHttpPsr7Message::parseMessage Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/psr7/README.md Demonstrates parsing a raw HTTP message string into an associative array using GuzzleHttp\Psr7\Message::parseMessage(). The resulting array includes the start line, headers, and body. ```php $messageString = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\"key\": \"value\"}"; $parsedMessage = GuzzleHttp\Psr7\Message::parseMessage($messageString); print_r($parsedMessage); ``` -------------------------------- ### Run Guzzle Promise Task Queue Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/promises/README.md Explains how to manually run the Guzzle promise task queue, which is necessary for asynchronous promise resolution, especially when integrating with event loops. ```php // Get the global task queue $queue = GuzzleHttp\Promise\Utils::queue(); $queue->run(); ``` -------------------------------- ### Track Page Views Automatically with hit() Source: https://context7.com/pirsch-analytics/pirsch-php-sdk/llms.txt Tracks a page view by automatically extracting visitor data from PHP's $_SERVER superglobal. Requires session to be started and the Pirsch\Client class. Returns null on success or the decoded JSON response on error. ```php hit(); // Page view successfully tracked // Returns null on success or decoded JSON response } catch (Exception $e) { error_log('Failed to track page view: ' . $e->getMessage()); } ``` -------------------------------- ### Retrieving Default Headers in Guzzle Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/guzzle/UPGRADING.md Illustrates how to retrieve default headers in Guzzle using the updated configuration path. This replaces the removed `getDefaultHeaders()` method. ```php $client->getConfig()->getPath('request.options/headers'); ``` -------------------------------- ### Retrieve Geographic Statistics with Pirsch PHP SDK Source: https://context7.com/pirsch-analytics/pirsch-php-sdk/llms.txt Fetches and displays visitor data by country, region, and city using the Pirsch PHP SDK. Requires client ID and secret for authentication. Allows filtering by country to get regional and city-level insights. ```php domain(); $filter = new Filter(); $filter->id = $domain->id; $filter->from = date('Y-m-d', strtotime('-30 days')); $filter->to = date('Y-m-d'); $filter->limit = 10; try { // Visitors by country $countries = $client->country($filter); echo "Top Countries:\n"; foreach ($countries as $country) { echo " " . $country->country_code . ": " . $country->visitors . " visitors\n"; } // Filter by country for regional breakdown $filter->country = 'US'; $regions = $client->region($filter); echo "\nUS Regions:\n"; foreach ($regions as $region) { echo " " . $region->region . ": " . $region->visitors . " visitors\n"; } // City-level data $cities = $client->city($filter); echo "\nTop US Cities:\n"; foreach ($cities as $city) { echo " " . $city->city . ": " . $city->visitors . " visitors\n"; } } catch (Exception $e) { error_log('Geographic statistics error: ' . $e->getMessage()); } ``` -------------------------------- ### Guzzle and React Promise Interoperability Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/promises/README.md Demonstrates how to integrate Guzzle promises with React promises. It shows how returning a React promise from a Guzzle promise's then() callback allows for recursive promise resolution. ```php // Create a React promise $deferred = new React\Promise\Deferred(); $reactPromise = $deferred->promise(); // Create a Guzzle promise that is fulfilled with a React promise. $guzzlePromise = new GuzzleHttp\Promise\Promise(); $guzzlePromise->then(function ($value) use ($reactPromise) { // Do something something with the value... // Return the React promise return $reactPromise; }); ``` -------------------------------- ### Query String Management in Guzzle Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/guzzle/UPGRADING.md Explains how query strings are handled in Guzzle 6, where they must be passed as strings or via the 'query' request option. It highlights the use of `http_build_query` and provides helper functions for parsing and building query strings. ```php // Query strings must now be passed into request objects as strings, or provided to // the `query` request option when creating requests with clients. // The `query` option uses PHP's `http_build_query` to convert an array to a string. // Helper functions: GuzzleHttp\Psr7\parse_query and GuzzleHttp\Psr7\build_query. ``` -------------------------------- ### Safely Get Stream Contents using GuzzleHttpPsr7Utils::tryGetContents (PHP) Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/psr7/README.md The tryGetContents method safely retrieves the contents of a given stream resource. It enhances the standard stream_get_contents function by adding an error handler that throws an exception on failure instead of raising a PHP warning. ```php $contents = GuzzleHttp\Psr7\Utils::tryGetContents($stream); ``` -------------------------------- ### Get Keyword Statistics with Pirsch PHP SDK Source: https://context7.com/pirsch-analytics/pirsch-php-sdk/llms.txt Retrieves top search keywords, clicks, and impressions from Google Search Console integration using the Pirsch PHP SDK. Requires client ID and secret for authentication. Filters can be applied for date ranges and limits. ```php domain(); $filter = new Filter(); $filter->id = $domain->id; $filter->from = date('Y-m-d', strtotime('-30 days')); $filter->to = date('Y-m-d'); $filter->limit = 20; try { // Search keywords (requires Google Search Console integration) $keywords = $client->keywords($filter); echo "Top Search Keywords:\n"; foreach ($keywords as $keyword) { echo " " . $keyword->keys . ": " . $keyword->clicks . " clicks, " . $keyword->impressions . " impressions\n"; } } catch (Exception $e) { error_log('Keyword statistics error: ' . $e->getMessage()); } ``` -------------------------------- ### Updating Default Headers in Guzzle Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/guzzle/UPGRADING.md Demonstrates how to update default headers in Guzzle, replacing the removed `setDefaultHeaders()` and `getDefaultHeaders()` methods. It shows the new approach using `getConfig()->setPath()` or `setDefaultOption()` for setting individual headers or all headers. ```php $client->getConfig()->setPath('request.options/headers/{header_name}', 'value'); $client->getConfig()->setPath('request.options/headers', array('header_name' => 'value')); $client->setDefaultOption('headers/{header_name}', 'value'); $client->setDefaultOption('headers', array('header_name' => 'value')); ``` -------------------------------- ### Static Utility Function Relocation in Guzzle Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/guzzle/UPGRADING.md Explains that static functions previously in `GuzzleHttpUtils` have been moved to namespaced functions under the `GuzzleHttp` namespace. This requires a Composer autoloader or including the functions.php file. ```php // Static functions in GuzzleHttp\Utils have been moved to namespaced functions under the GuzzleHttp namespace. // This requires either a Composer based autoloader or you to include functions.php. ``` -------------------------------- ### Middleware Equivalents for Guzzle Subscribers Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/guzzle/UPGRADING.md Shows how Guzzle 6 subscribers have been replaced by middleware functions. This section lists common subscribers and their corresponding middleware equivalents, facilitating the transition to the new middleware system. ```php // GuzzleHttp\Subscriber\Cookie is now provided by GuzzleHttp\Middleware::cookies // GuzzleHttp\Subscriber\HttpError is now provided by GuzzleHttp\Middleware::httpError // GuzzleHttp\Subscriber\History is now provided by GuzzleHttp\Middleware::history // GuzzleHttp\Subscriber\Mock is now provided by GuzzleHttp\Handler\MockHandler // GuzzleHttp\Subscriber\Prepare is now provided by GuzzleHttp\PrepareBodyMiddleware // GuzzleHttp\Subscriber\Redirect is now provided by GuzzleHttp\RedirectMiddleware ``` -------------------------------- ### Update Guzzle Inspector to Collection in PHP Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/guzzle/UPGRADING.md Demonstrates the refactoring of Guzzle client factory to use \Guzzle\Common\Collection::fromConfig instead of \Guzzle\Service\Inspector::fromConfig. This change impacts configuration loading and validation within the SDK. No external dependencies are introduced, and the input remains a configuration array. ```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; } } ``` -------------------------------- ### Convert XML to JSON API Descriptions Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/guzzlehttp/guzzle/UPGRADING.md This snippet shows the transformation of an XML service description into a JSON format. The XML defines API commands with their HTTP methods, URIs, and parameters, while the JSON represents the same information in a structured, machine-readable format. ```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 ``` ```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" } } } } ``` -------------------------------- ### Psr\Http\Message\MessageInterface Methods Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/psr/http-message/docs/PSR7-Interfaces.md Details the methods available for the `MessageInterface`, which represents a generic HTTP message. ```APIDOC ## `Psr\Http\Message\MessageInterface` Methods ### Description Provides methods for interacting with the core components of an HTTP message, such as protocol version, headers, and body. ### Methods - **`getProtocolVersion()`**: Retrieve HTTP protocol version (e.g., '1.0' or '1.1'). - **`withProtocolVersion($version)`**: Returns a new message instance with the specified HTTP protocol version. - **`getHeaders()`**: Retrieve all HTTP Headers. Refer to [Request Header List](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields) and [Response Header List](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Response_fields). - **`hasHeader($name)`**: Checks if an HTTP Header with the given name exists. - **`getHeader($name)`**: Retrieves an array containing the values for a single header. - **`getHeaderLine($name)`**: Retrieves a comma-separated string of the values for a single header. - **`withHeader($name, $value)`**: Returns a new message instance with the specified HTTP Header. If the header already exists, its value is replaced. - **`withAddedHeader($name, $value)`**: Returns a new message instance with the specified value appended to the given header. If the header does not exist, it is created. - **`withoutHeader($name)`**: Removes the HTTP Header with the specified name. - **`getBody()`**: Retrieves the HTTP Message Body. Returns an object implementing `StreamInterface`. - **`withBody(StreamInterface $body)`**: Returns a new message instance with the specified HTTP Message Body. ``` -------------------------------- ### Prepend to Stream Using Contents as String (PHP) Source: https://github.com/pirsch-analytics/pirsch-php-sdk/blob/master/vendor/psr/http-message/docs/PSR7-Usage.md This method shows how to prepend data to a response body stream by first extracting its entire content into a string, prepending the new data to this string, rewinding the stream, and then writing the modified string back. This approach simplifies the process by treating the stream content as a single string. ```php $body = $response->getBody(); $body->rewind(); $contents = $body->getContents(); // efabcd $contents = 'ef'.$contents; $body->rewind(); $body->write($contents); ```