### Setup BrowscapPHP with League Flysystem and Scrapbook Cache Source: https://github.com/browscap/browscap-php/blob/7.8.x/README.md Example of setting up BrowscapPHP using League Flysystem for local file storage and MatthiasMullie's Scrapbook for PSR-16 caching. ```php $fileCache = new \League\Flysystem\Local\LocalFilesystemAdapter($cacheDir); $filesystem = new \League\Flysystem\Filesystem($fileCache); $cache = new \MatthiasMullie\Scrapbook\Psr16\SimpleCache( new \MatthiasMullie\Scrapbook\Adapters\Flysystem($filesystem) ); $logger = new \Monolog\Logger('name'); $bc = new \BrowscapPHP\Browscap($cache, $logger); $result = $bc->getBrowser(); ``` -------------------------------- ### Install browscap-php via Composer Source: https://github.com/browscap/browscap-php/blob/7.8.x/README.md Run this command to install the library using Composer. ```shell composer require browscap/browscap-php ``` -------------------------------- ### Get browser information from a sample user agent Source: https://github.com/browscap/browscap-php/blob/7.8.x/README.md Instantiate Browscap with cache and logger, then retrieve browser information for a specific user agent string. ```php $bc = new \BrowscapPHP\Browscap($cache, $logger); $current_browser = $bc->getBrowser($the_user_agent); ``` -------------------------------- ### Get browser information from SERVER variable Source: https://github.com/browscap/browscap-php/blob/7.8.x/README.md Instantiate Browscap and retrieve browser information using the global $_SERVER variable for the user agent. ```php $bc = new \BrowscapPHP\Browscap(); $current_browser = $bc->getBrowser(); ``` -------------------------------- ### Get Browser Capabilities for a User Agent Source: https://context7.com/browscap/browscap-php/llms.txt Parses a user agent string to return browser capabilities as a stdClass object. If no user agent is provided, it attempts to detect it from $_SERVER headers. Ensure the cache is populated by running BrowscapUpdater::update() first. ```php use BrowscapPHP\Browscap; use BrowscapPHP\Exception as BrowscapException; // $browscap constructed as shown above, cache already populated via BrowscapUpdater $ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' . '(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'; try { $info = $browscap->getBrowser($ua); } catch (BrowscapException $e) { // Cache not warm — run BrowscapUpdater::update() first exit($e->getMessage()); } echo $info->browser; // "Chrome" echo $info->version; // "124.0" echo $info->platform; // "Win10" echo $info->ismobiledevice // false (bool) ? 'mobile' : 'desktop'; echo $info->crawler // false ? 'bot' : 'human'; // Auto-detect from $_SERVER (no argument needed in a real HTTP context) $serverInfo = $browscap->getBrowser(); var_dump($serverInfo->browser); ``` -------------------------------- ### Determine Property Type and Format Values Source: https://context7.com/browscap/browscap-php/llms.txt Get the data type of a browscap property and format values accordingly. This is used internally for INI parsing and value coercion. ```php use BrowscapPHP\Data\PropertyHolder; $holder = new PropertyHolder(); echo $holder->getPropertyType('Browser'); // "string" echo $holder->getPropertyType('Version'); // "number" echo $holder->getPropertyType('isMobileDevice'); // "boolean" echo $holder->getPropertyType('Browser_Bits'); // "generic" // Used with PropertyFormatter for value coercion use BrowscapPHP\Data\PropertyFormatter; $formatter = new PropertyFormatter($holder); var_dump($formatter->formatPropertyValue('true', 'isMobileDevice')); // bool(true) var_dump($formatter->formatPropertyValue('1', 'Crawler')); // bool(true) var_dump($formatter->formatPropertyValue('124', 'Version')); // string("124") ``` -------------------------------- ### Initialize BrowscapPHP with Cache and Logger Source: https://github.com/browscap/browscap-php/blob/7.8.x/README.md Instantiate the Browscap class with a PSR-16 compatible cache and a PSR-3 compatible logger. ```php $cache = new \MatthiasMullie\Scrapbook\Psr16\SimpleCache($doctrineFileCache); // or maybe any other PSR-16 compatible caches $logger = new \Monolog\Logger('name'); // or maybe any other PSR-3 compatible logger $browscap = new \BrowscapPHP\Browscap($cache, $logger); $info = $browscap->getBrowser(); ``` -------------------------------- ### Instantiate Browscap with Cache and Logger Source: https://context7.com/browscap/browscap-php/llms.txt Instantiates the main browser detection class using PSR-16 cache and PSR-3 logger implementations. Ensure the cache directory is writable. ```php use BrowscapPHP\Browscap; use MatthiasMullie\Scrapbook\Adapters\Flysystem as FlysystemAdapter; use MatthiasMullie\Scrapbook\Psr16\SimpleCache; use League\Flysystem\Filesystem; use League\Flysystem\Local\LocalFilesystemAdapter; use Monolog\Logger; use Monolog\Handler\StreamHandler; $cacheDir = '/tmp/browscap-cache'; $flysystem = new Filesystem(new LocalFilesystemAdapter($cacheDir)); $pool = new FlysystemAdapter($flysystem); $cache = new SimpleCache($pool); $logger = new Logger('browscap'); $logger->pushHandler(new StreamHandler('php://stderr', Logger::WARNING)); $browscap = new Browscap($cache, $logger); ``` -------------------------------- ### Fetch browscap.ini file Source: https://github.com/browscap/browscap-php/blob/7.8.x/README.md Use this CLI command to download the browscap.ini file. ```shell vendor/bin/browscap-php browscap:fetch ``` -------------------------------- ### CLI Commands for Browscap PHP Source: https://context7.com/browscap/browscap-php/llms.txt The CLI binary provides commands for updating, fetching, checking, and parsing browscap data. Use the --cache option to specify a custom cache directory. ```bash # Download and convert browscap.ini into cache in one step (standard file) vendor/bin/browscap-php browscap:update # Download the full browscap.ini to a custom cache directory vendor/bin/browscap-php browscap:update --remote-file Full_PHP_BrowscapINI --cache ./my-browscap-cache # Two-step: download the raw INI file, then convert it vendor/bin/browscap-php browscap:fetch --file /tmp/browscap.ini vendor/bin/browscap-php browscap:convert --file /tmp/browscap.ini --cache ./my-browscap-cache # Check if a newer version is available remotely vendor/bin/browscap-php browscap:check-update # Exit codes: 1=no cache, 2=no new version, 3-5=errors # Parse a specific user agent string vendor/bin/browscap-php browscap:parse \ --user-agent "Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 Chrome/124.0 Mobile Safari/537.36" ``` -------------------------------- ### Browscap::__construct Source: https://context7.com/browscap/browscap-php/llms.txt Instantiates the main browser detection class. Accepts any PSR-16 simple cache implementation and any PSR-3 logger. Internally wraps the cache with BrowscapCache for versioned key management and defaults to the PhpGetBrowser formatter. ```APIDOC ## Browscap::__construct(CacheInterface $cache, LoggerInterface $logger) ### Description Instantiates the main browser detection class. Accepts any PSR-16 simple cache implementation and any PSR-3 logger. Internally wraps the cache with `BrowscapCache` for versioned key management and defaults to the `PhpGetBrowser` formatter. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php use BrowscapPHP\Browscap; use MatthiasMullie\Scrapbook\Adapters\Flysystem as FlysystemAdapter; use MatthiasMullie\Scrapbook\Psr16\SimpleCache; use League\Flysystem\Filesystem; use League\Flysystem\Local\LocalFilesystemAdapter; use Monolog\Logger; use Monolog\Handler\StreamHandler; $cacheDir = '/tmp/browscap-cache'; $flysystem = new Filesystem(new LocalFilesystemAdapter($cacheDir)); $pool = new FlysystemAdapter($flysystem); $cache = new SimpleCache($pool); $logger = new Logger('browscap'); $logger->pushHandler(new StreamHandler('php://stderr', Logger::WARNING)); $browscap = new Browscap($cache, $logger); ``` ### Response None ``` -------------------------------- ### Injecting and Retrieving Parsers in Browscap Source: https://context7.com/browscap/browscap-php/llms.txt Demonstrates how to inject a custom parser or retrieve the default parser instance. The default parser uses GetPattern and GetData for parsing. ```php use BrowscapPHP\Browscap; use BrowscapPHP\Parser\Ini as IniParser; use BrowscapPHP\Parser\Helper\GetPattern; use BrowscapPHP\Parser\Helper\GetData; use BrowscapPHP\Cache\BrowscapCache; use BrowscapPHP\Helper\Quoter; use BrowscapPHP\Formatter\PhpGetBrowser; $browscap = new Browscap($cache, $logger); // Retrieve default parser (lazily created on first call) $parser = $browscap->getParser(); // instanceof Parser\Ini // Or inject a custom-configured parser $bcCache = new BrowscapCache($cache, $logger); $patternHelper = new GetPattern($bcCache, $logger); $dataHelper = new GetData($bcCache, $logger, new Quoter()); $formatter = new PhpGetBrowser(); $browscap->setParser(new IniParser($patternHelper, $dataHelper, $formatter)); ``` -------------------------------- ### Convert browscap.ini file Source: https://github.com/browscap/browscap-php/blob/7.8.x/README.md Use this CLI command to convert the downloaded browscap.ini file into a cache format. ```shell vendor/bin/browscap-php browscap:convert ``` -------------------------------- ### Instantiating BrowscapUpdater with Custom Client and Timeout Source: https://context7.com/browscap/browscap-php/llms.txt Shows how to instantiate the BrowscapUpdater with a custom Guzzle HTTP client and a specified connect timeout. This updater is responsible for fetching and converting browscap.ini data. ```php use BrowscapPHP\BrowscapUpdater; use GuzzleHttp\Client; // Default client with proxy configuration $client = new Client([ 'proxy' => [ 'http' => 'tcp://proxy.example.com:8080', 'https' => 'tcp://proxy.example.com:8080', ], ]); $updater = new BrowscapUpdater($cache, $logger, $client, connectTimeout: 10); ``` -------------------------------- ### BrowscapUpdater Constructor Source: https://context7.com/browscap/browscap-php/llms.txt Instantiates the updater responsible for fetching and converting `browscap.ini` data into the cache. Accepts an optional Guzzle-compatible HTTP client and a connect timeout in seconds. ```APIDOC ## `BrowscapUpdater::__construct(CacheInterface $cache, LoggerInterface $logger, ?ClientInterface $client = null, int $connectTimeout = 5)` ### Description Instantiates the updater responsible for fetching and converting `browscap.ini` data into the cache. Accepts an optional Guzzle-compatible HTTP client (defaults to `GuzzleHttp\Client`) and a connect timeout in seconds. Use this class to prime or refresh the cache before using `Browscap`. ### Parameters - **cache** (CacheInterface) - Required - The cache implementation. - **logger** (LoggerInterface) - Required - The logger implementation. - **client** (ClientInterface) - Optional - An optional Guzzle-compatible HTTP client. - **connectTimeout** (int) - Optional - The connection timeout in seconds (defaults to 5). ### Example ```php use BrowscapPHP\BrowscapUpdater; use GuzzleHttp\Client; // Default client with proxy configuration $client = new Client([ 'proxy' => [ 'http' => 'tcp://proxy.example.com:8080', 'https' => 'tcp://proxy.example.com:8080', ], ]); $updater = new BrowscapUpdater($cache, $logger, $client, connectTimeout: 10); ``` ``` -------------------------------- ### Converting Local INI File to Browscap Cache Source: https://context7.com/browscap/browscap-php/llms.txt Reads a locally stored browscap.ini file and parses it into the cache. Use this after fetch() to separate download and conversion steps. Handles exceptions for missing or unreadable files. ```php use BrowscapPHP\BrowscapUpdater; use BrowscapPHP\Exception\FileNotFoundException; use BrowscapPHP\Exception\FileNameMissingException; use BrowscapPHP\Exception\ErrorReadingFileException; $updater = new BrowscapUpdater($cache, $logger); $localFile = '/tmp/browscap.ini'; try { $updater->convertFile($localFile); echo "Cache populated from $localFile\n"; } catch (FileNameMissingException $e) { echo "No file name provided.\n"; } catch (FileNotFoundException $e) { echo "File not found or not readable: " . $e->getMessage() . "\n"; } catch (ErrorReadingFileException $e) { echo "Error reading file: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Updating Browscap Cache with Different INI Variants Source: https://context7.com/browscap/browscap-php/llms.txt Demonstrates downloading the remote browscap.ini directly into the cache. It checks for newer versions and supports different file variants like PHP_INI, PHP_INI_FULL, and PHP_INI_LITE. ```php use BrowscapPHP\BrowscapUpdater; use BrowscapPHP\Helper\IniLoaderInterface; use BrowscapPHP\Exception\FetcherException; $updater = new BrowscapUpdater($cache, $logger); try { // Download the standard file (default) $updater->update(IniLoaderInterface::PHP_INI); // Or download the full file for more detailed data // $updater->update(IniLoaderInterface::PHP_INI_FULL); // Or download the lite file for a smaller cache footprint // $updater->update(IniLoaderInterface::PHP_INI_LITE); echo "Cache updated successfully.\n"; } catch (FetcherException $e) { echo "Failed to fetch remote data: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Configure Guzzle client for proxy Source: https://github.com/browscap/browscap-php/blob/7.8.x/README.md Set up a Guzzle HTTP client with proxy configuration for use with BrowscapUpdater. ```php $proxyConfig = [ 'proxy' => [ 'http' => 'tcp://localhost:8125', 'https' => 'tcp://localhost:8124', ], ]; $client = new \GuzzleHttp\Client($proxyConfig); $bcu = new BrowscapUpdater(); $bcu->setClient($client); ``` -------------------------------- ### Update Browscap using full browscap.ini Source: https://github.com/browscap/browscap-php/blob/7.8.x/README.md This snippet demonstrates how to use the BrowscapUpdater to update the cache with the full browscap.ini file. ```php $bc = new \BrowscapPHP\BrowscapUpdater(); $bc->update(\BrowscapPHP\Helper\IniLoaderInterface::PHP_INI_FULL); ``` -------------------------------- ### CLI Commands Source: https://context7.com/browscap/browscap-php/llms.txt The CLI binary exposes all major operations as Symfony Console commands. The `--cache` option overrides the default `resources/` cache directory for all commands. ```APIDOC ## CLI Commands (`bin/browscap-php`) The CLI binary exposes all major operations as Symfony Console commands. The `--cache` option overrides the default `resources/` cache directory for all commands. ```bash # Download and convert browscap.ini into cache in one step (standard file) vendor/bin/browscap-php browscap:update # Download the full browscap.ini to a custom cache directory vendor/bin/browscap-php browscap:update --remote-file Full_PHP_BrowscapINI --cache ./my-browscap-cache # Two-step: download the raw INI file, then convert it vendor/bin/browscap-php browscap:fetch --file /tmp/browscap.ini vendor/bin/browscap-php browscap:convert --file /tmp/browscap.ini --cache ./my-browscap-cache # Check if a newer version is available remotely vendor/bin/browscap-php browscap:check-update # Exit codes: 1=no cache, 2=no new version, 3-5=errors # Parse a specific user agent string vendor/bin/browscap-php browscap:parse \ --user-agent "Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 Chrome/124.0 Mobile Safari/537.36" ``` ``` -------------------------------- ### Update browscap.ini file and convert Source: https://github.com/browscap/browscap-php/blob/7.8.x/README.md This command fetches the latest browscap.ini file and converts it into a cache in a single step. ```shell vendor/bin/browscap-php browscap:update ``` -------------------------------- ### Fetching Remote INI File to Local Storage Source: https://context7.com/browscap/browscap-php/llms.txt Downloads the remote browscap.ini and saves it as a local file without parsing it into the cache. This is useful for later conversion using convertFile(). ```php use BrowscapPHP\BrowscapUpdater; use BrowscapPHP\Helper\IniLoaderInterface; use BrowscapPHP\Exception\FetcherException; $updater = new BrowscapUpdater($cache, $logger); $localFile = '/tmp/browscap.ini'; try { $updater->fetch($localFile, IniLoaderInterface::PHP_INI_FULL); echo "INI file saved to $localFile\n"; } catch (FetcherException $e) { echo "Fetch failed: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Parse INI String into Cache Source: https://context7.com/browscap/browscap-php/llms.txt Use this method when the INI content is available as a string, not a file. It directly populates the cache without needing a local file. ```php use BrowscapPHP\BrowscapUpdater; $updater = new BrowscapUpdater($cache, $logger); $iniString = file_get_contents('/path/to/custom/browscap.ini'); if ($iniString !== false) { $updater->convertString($iniString); echo "Cache populated from custom INI string.\n"; } ``` -------------------------------- ### Browscap::setFormatter Source: https://context7.com/browscap/browscap-php/llms.txt Replaces the default PhpGetBrowser output formatter with a custom or alternative formatter. Must be called before getBrowser(). ```APIDOC ## Browscap::setFormatter(FormatterInterface $formatter): void ### Description Replaces the default `PhpGetBrowser` output formatter with a custom or alternative formatter. Must be called before `getBrowser()`. Two built-in formatters are provided: `PhpGetBrowser` (default, mirrors native `get_browser()` output) and `LegacyFormatter` (backwards-compatible with 2.x, preserves original property casing and optionally lowercases keys). ### Method PUT (conceptual, as it modifies internal state) ### Endpoint N/A (Method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **formatter** (FormatterInterface) - Required - An instance of a formatter implementing `FormatterInterface`. ### Request Example ```php use BrowscapPHP\Browscap; use BrowscapPHP\Formatter\LegacyFormatter; $browscap = new Browscap($cache, $logger); // Use LegacyFormatter with lowercase keys $browscap->setFormatter(new LegacyFormatter(['lowercase' => true])); $info = $browscap->getBrowser('Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)'); // LegacyFormatter preserves all raw INI keys (not just the default set) echo $info->browser; echo $info->platform; ``` ### Response None ``` -------------------------------- ### Browscap Parser Management Source: https://context7.com/browscap/browscap-php/llms.txt Allows injecting a custom parser or retrieving the default `Parser\Ini` instance. The default parser uses `GetPattern` and `GetData`. You can override this to implement a custom parsing strategy. ```APIDOC ## `Browscap::setParser(ParserInterface $parser): void` / `Browscap::getParser(): ParserInterface` ### Description Injects a custom parser or retrieves the lazily-instantiated default `Parser\Ini` instance. The default parser uses `GetPattern` (finds candidate patterns from cache) and `GetData` (retrieves property data for matched patterns). Override to use a completely custom parsing strategy. ### Method - `setParser(ParserInterface $parser): void` - `getParser(): ParserInterface` ### Example ```php use BrowscapPHP\Browscap; use BrowscapPHP\Parser\Ini as IniParser; use BrowscapPHP\Parser\Helper\GetPattern; use BrowscapPHP\Parser\Helper\GetData; use BrowscapPHP\Cache\BrowscapCache; use BrowscapPHP\Helper\Quoter; use BrowscapPHP\Formatter\PhpGetBrowser; $browscap = new Browscap($cache, $logger); // Retrieve default parser (lazily created on first call) $parser = $browscap->getParser(); // instanceof Parser\Ini // Or inject a custom-configured parser $bcCache = new BrowscapCache($cache, $logger); $patternHelper = new GetPattern($bcCache, $logger); $dataHelper = new GetData($bcCache, $logger, new Quoter()); $formatter = new PhpGetBrowser(); $browscap->setParser(new IniParser($patternHelper, $dataHelper, $formatter)); ``` ``` -------------------------------- ### BrowscapUpdater::fetch Source: https://context7.com/browscap/browscap-php/llms.txt Downloads the remote `browscap.ini` and saves it as a local file, without parsing it into the cache. This is useful when you want to store the raw INI file for later conversion using `convertFile()`. The file is only written if the remote version is newer than the cached version. ```APIDOC ## `BrowscapUpdater::fetch(string $file, string $remoteFile = IniLoaderInterface::PHP_INI): void` ### Description Downloads the remote `browscap.ini` and saves it as a local file (without parsing into cache). Useful when you want to store the raw INI file for later conversion via `convertFile()`. Only writes the file if the remote version is newer than the cached version. ### Parameters - **file** (string) - Required - The local path where the INI file will be saved. - **remoteFile** (string) - Optional - The variant of the browscap.ini file to download. Defaults to `IniLoaderInterface::PHP_INI`. ### Example ```php use BrowscapPHP\BrowscapUpdater; use BrowscapPHP\Helper\IniLoaderInterface; use BrowscapPHP\Exception\FetcherException; $updater = new BrowscapUpdater($cache, $logger); $localFile = '/tmp/browscap.ini'; try { $updater->fetch($localFile, IniLoaderInterface::PHP_INI_FULL); echo "INI file saved to $localFile\n"; } catch (FetcherException $e) { echo "Fetch failed: " . $e->getMessage() . "\n"; } ``` ``` -------------------------------- ### BrowscapUpdater::convertFile Source: https://context7.com/browscap/browscap-php/llms.txt Reads a locally stored `browscap.ini` file and parses it into the cache. This method is intended to be used after `fetch()` to separate the download and conversion steps. It throws specific exceptions for missing file names, unreadable files, or read errors. ```APIDOC ## `BrowscapUpdater::convertFile(string $iniFile): void` ### Description Reads a locally stored `browscap.ini` file and parses it into the cache. Use this after `fetch()` to separate the download and conversion steps. Throws typed exceptions for missing file name, unreadable file, or read errors. ### Parameters - **iniFile** (string) - Required - The path to the local `browscap.ini` file. ### Example ```php use BrowscapPHP\BrowscapUpdater; use BrowscapPHP\Exception\FileNotFoundException; use BrowscapPHP\Exception\FileNameMissingException; use BrowscapPHP\Exception\ErrorReadingFileException; $updater = new BrowscapUpdater($cache, $logger); $localFile = '/tmp/browscap.ini'; try { $updater->convertFile($localFile); echo "Cache populated from $localFile\n"; } catch (FileNameMissingException $e) { echo "No file name provided.\n"; } catch (FileNotFoundException $e) { echo "File not found or not readable: " . $e->getMessage() . "\n"; } catch (ErrorReadingFileException $e) { echo "Error reading file: " . $e->getMessage() . "\n"; } ``` ``` -------------------------------- ### BrowscapCache API for Cache Introspection Source: https://context7.com/browscap/browscap-php/llms.txt Wraps a PSR-16 CacheInterface to manage versioned cache keys and metadata. Use this for direct cache access and flushing. ```php use BrowscapPHP\Cache\BrowscapCache; $bcCache = new BrowscapCache($cache, $logger); // Read version, release date, and type metadata from cache $version = $bcCache->getVersion(); // e.g. 7001 $releaseDate = $bcCache->getReleaseDate(); // e.g. "Mon, 01 Jan 2024 00:00:00 +0000" $type = $bcCache->getType(); // e.g. "PHP" echo "Browscap cache version: $version, released: $releaseDate, type: $type\n"; // Low-level item access (internal use) $success = null; $value = $bcCache->getItem('browscap.version', false, $success); if ($success) { echo "Raw version from cache: $value\n"; } // Flush the entire cache $bcCache->flush(); ``` -------------------------------- ### Browscap::getBrowser Source: https://context7.com/browscap/browscap-php/llms.txt Parses a user agent string and returns a stdClass object with browser capability properties. If $userAgent is null, the user agent is detected automatically from $_SERVER headers. Throws \BrowscapPHP\Exception if the cache is empty. ```APIDOC ## Browscap::getBrowser(?string $userAgent = null): stdClass ### Description Parses a user agent string and returns a `stdClass` object with browser capability properties. If `$userAgent` is `null`, the user agent is detected automatically from `$_SERVER` headers (checking `HTTP_X_DEVICE_USER_AGENT`, `HTTP_X_ORIGINAL_USER_AGENT`, `HTTP_X_OPERAMINI_PHONE_UA`, `HTTP_X_SKYFIRE_PHONE`, `HTTP_X_BOLT_PHONE_UA`, `HTTP_USER_AGENT` in that order). Throws `\BrowscapPHP\Exception` if the cache is empty (i.e., no update has been run). ### Method GET (conceptual, as it reads from cache) ### Endpoint N/A (Method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php use BrowscapPHP\Browscap; use BrowscapPHP\Exception as BrowscapException; // $browscap constructed as shown above, cache already populated via BrowscapUpdater $ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '. '(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'; try { $info = $browscap->getBrowser($ua); } catch (BrowscapException $e) { // Cache not warm — run BrowscapUpdater::update() first exit($e->getMessage()); } echo $info->browser; echo $info->version; echo $info->platform; echo $info->ismobiledevice ? 'mobile' : 'desktop'; echo $info->crawler ? 'bot' : 'human'; // Auto-detect from $_SERVER (no argument needed in a real HTTP context) $serverInfo = $browscap->getBrowser(); var_dump($serverInfo->browser); ``` ### Response #### Success Response (200) - **browser** (string) - The name of the browser. - **version** (string) - The version of the browser. - **platform** (string) - The operating system platform. - **ismobiledevice** (bool) - Indicates if the device is mobile. - **crawler** (bool) - Indicates if the user agent is a crawler/bot. #### Response Example ```json { "browser": "Chrome", "version": "124.0", "platform": "Win10", "ismobiledevice": false, "crawler": false } ``` ### Error Handling - **BrowscapException**: Thrown if the cache is empty and no update has been run. ``` -------------------------------- ### Check for browscap.ini updates via CLI Source: https://github.com/browscap/browscap-php/blob/7.8.x/README.md Use this command to check if a new version of the browscap.ini file is available without downloading it. ```shell vendor/bin/browscap-php browscap:check-update ``` -------------------------------- ### Parse User Agent String Source: https://github.com/browscap/browscap-php/blob/7.8.x/README.md Parses a given user agent string and outputs the result to the console. The 'user-agent' option is required, and 'cache' can specify a custom cache directory. ```bash vendor/bin/browscap-php browscap:parse ``` -------------------------------- ### BrowscapUpdater::update Source: https://context7.com/browscap/browscap-php/llms.txt Downloads the remote `browscap.ini` directly into the cache in one step. It checks the remote version first and returns if no newer version is available. Supports different variants of the `browscap.ini` file. ```APIDOC ## `BrowscapUpdater::update(string $remoteFile = IniLoaderInterface::PHP_INI): void` ### Description Downloads the remote `browscap.ini` directly into the cache in one step, skipping the local file system. Checks the remote version first; if no newer version is available, the method returns immediately without writing to the cache. Three remote file variants are available via `IniLoaderInterface` constants. ### Parameters - **remoteFile** (string) - Optional - The variant of the browscap.ini file to download. Defaults to `IniLoaderInterface::PHP_INI`. ### Example ```php use BrowscapPHP\BrowscapUpdater; use BrowscapPHP\Helper\IniLoaderInterface; use BrowscapPHP\Exception\FetcherException; $updater = new BrowscapUpdater($cache, $logger); try { // Download the standard file (default) $updater->update(IniLoaderInterface::PHP_INI); // Or download the full file for more detailed data // $updater->update(IniLoaderInterface::PHP_INI_FULL); // Or download the lite file for a smaller cache footprint // $updater->update(IniLoaderInterface::PHP_INI_LITE); echo "Cache updated successfully.\n"; } catch (FetcherException $e) { echo "Failed to fetch remote data: " . $e->getMessage() . "\n"; } ``` ``` -------------------------------- ### Set Custom Formatter for Browser Output Source: https://context7.com/browscap/browscap-php/llms.txt Replaces the default formatter with a custom one, such as LegacyFormatter, before calling getBrowser(). LegacyFormatter preserves original property casing and can lowercase keys. ```php use BrowscapPHP\Browscap; use BrowscapPHP\Formatter\LegacyFormatter; $browscap = new Browscap($cache, $logger); // Use LegacyFormatter with lowercase keys $browscap->setFormatter(new LegacyFormatter(['lowercase' => true])); $info = $browscap->getBrowser('Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)'); // LegacyFormatter preserves all raw INI keys (not just the default set) echo $info->browser; // "Safari" echo $info->platform; // "iOS" ``` -------------------------------- ### Update Cache with Full Browscap INI Source: https://github.com/browscap/browscap-php/blob/7.8.x/README.md Updates the Browscap cache using the full INI file from the remote source. This command specifies the 'Full_PHP_BrowscapINI' option for the remote file. ```bash vendor/bin/browscap-php browscap:update --remote-file Full_PHP_BrowscapINI ``` -------------------------------- ### Check for Browscap Update Source: https://context7.com/browscap/browscap-php/llms.txt This method checks for a newer version of the browscap.ini file. It handles exceptions for missing cache, no new versions, or network errors, and can trigger an update. ```php use BrowscapPHP\BrowscapUpdater; use BrowscapPHP\Exception\NoCachedVersionException; use BrowscapPHP\Exception\NoNewVersionException; use BrowscapPHP\Exception\FetcherException; $updater = new BrowscapUpdater($cache, $logger); try { $currentVersion = $updater->checkUpdate(); echo "Update available! Current cached version: $currentVersion\n"; $updater->update(); // proceed to update } catch (NoCachedVersionException $e) { echo "No local cache yet — running initial update.\n"; $updater->update(); } catch (NoNewVersionException $e) { echo "Already up to date.\n"; } catch (FetcherException $e) { echo "Network error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### BrowscapCache API Source: https://context7.com/browscap/browscap-php/llms.txt The BrowscapCache class wraps any PSR-16 CacheInterface and provides versioned cache key management, metadata accessors, and serialization. It is used internally by both Browscap and BrowscapUpdater, but can be used directly for cache introspection. ```APIDOC ## `BrowscapCache` — Cache Proxy API `BrowscapCache` wraps any PSR-16 `CacheInterface` and provides versioned cache key management, metadata accessors, and serialization. It is used internally by both `Browscap` and `BrowscapUpdater`, but can be used directly for cache introspection. ```php use BrowscapPHP\Cache\BrowscapCache; $bcCache = new BrowscapCache($cache, $logger); // Read version, release date, and type metadata from cache $version = $bcCache->getVersion(); // e.g. 7001 $releaseDate = $bcCache->getReleaseDate(); // e.g. "Mon, 01 Jan 2024 00:00:00 +0000" $type = $bcCache->getType(); // e.g. "PHP" echo "Browscap cache version: $version, released: $releaseDate, type: $type\n"; // Low-level item access (internal use) $success = null; $value = $bcCache->getItem('browscap.version', false, $success); if ($success) { echo "Raw version from cache: $value\n"; } // Flush the entire cache $bcCache->flush(); ``` ``` -------------------------------- ### Update Cache with Custom Directory Source: https://github.com/browscap/browscap-php/blob/7.8.x/README.md Updates the Browscap cache using a specified custom directory for the cache files. This avoids the cache being cleared during composer updates. The 'cache' option sets the custom path. ```bash vendor/bin/browscap-php browscap:update --cache ./browscap-cache ``` -------------------------------- ### BrowscapUpdater::convertString Source: https://context7.com/browscap/browscap-php/llms.txt Parses an in-memory INI string directly into the cache. This is useful when the INI content is obtained from a source other than a local file or the standard remote URL. ```APIDOC ## `BrowscapUpdater::convertString(string $iniString): void` Parses an in-memory INI string directly into the cache. Useful when you obtain the INI content from a source other than a local file or the standard remote URL (e.g., a custom CDN, a test fixture, or an embedded resource). ```php use BrowscapPHP\BrowscapUpdater; $updater = new BrowscapUpdater($cache, $logger); $iniString = file_get_contents('/path/to/custom/browscap.ini'); if ($iniString !== false) { $updater->convertString($iniString); echo "Cache populated from custom INI string.\n"; } ``` ``` -------------------------------- ### BrowscapUpdater::checkUpdate Source: https://context7.com/browscap/browscap-php/llms.txt Checks if a newer version of the remote browscap.ini is available compared to the cached version. It returns the current cached version integer if an update is available. ```APIDOC ## `BrowscapUpdater::checkUpdate(): ?int` Checks whether a newer version of the remote `browscap.ini` is available compared to the cached version. Returns the current cached version integer if an update is available. Throws `NoCachedVersionException` if no cache exists yet, `NoNewVersionException` if already up to date, or `FetcherException` on network errors. ```php use BrowscapPHP\BrowscapUpdater; use BrowscapPHP\Exception\NoCachedVersionException; use BrowscapPHP\Exception\NoNewVersionException; use BrowscapPHP\Exception\FetcherException; $updater = new BrowscapUpdater($cache, $logger); try { $currentVersion = $updater->checkUpdate(); echo "Update available! Current cached version: $currentVersion\n"; $updater->update(); // proceed to update } catch (NoCachedVersionException $e) { echo "No local cache yet — running initial update.\n"; $updater->update(); } catch (NoNewVersionException $e) { echo "Already up to date.\n"; } catch (FetcherException $e) { echo "Network error: " . $e->getMessage() . "\n"; } ``` ``` -------------------------------- ### PropertyHolder::getPropertyType Source: https://context7.com/browscap/browscap-php/llms.txt Returns the data type for any browscap property name. This is used internally during INI parsing and property formatting to ensure correct value coercion. ```APIDOC ## `PropertyHolder::getPropertyType(string $propertyName): string` Returns the data type (`TYPE_STRING`, `TYPE_NUMBER`, `TYPE_BOOLEAN`, or `TYPE_GENERIC`) for any browscap property name. Used internally during INI parsing and property formatting to ensure correct value coercion. ```php use BrowscapPHP\Data\PropertyHolder; $holder = new PropertyHolder(); echo $holder->getPropertyType('Browser'); // "string" echo $holder->getPropertyType('Version'); // "number" echo $holder->getPropertyType('isMobileDevice'); // "boolean" echo $holder->getPropertyType('Browser_Bits'); // "generic" // Used with PropertyFormatter for value coercion use BrowscapPHP\Data\PropertyFormatter; $formatter = new PropertyFormatter($holder); var_dump($formatter->formatPropertyValue('true', 'isMobileDevice')); // bool(true) var_dump($formatter->formatPropertyValue('1', 'Crawler')); // bool(true) var_dump($formatter->formatPropertyValue('124', 'Version')); // string("124") ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.