openxtrem / browscap
Standalone replacement for php's native get_browser() function
Requires
- php: 8.3.* | 8.4.*
- browscap/browscap-php: ^7.4
- openxtrem/cache: ^6.0
Requires (Dev)
- backendtea/phpstan-multiple-error-formatter: ^1.0
- phpstan/extension-installer: ^1.4
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^12.5
README
About
Requires browscap/browscap-php packages, converts PHP_BrowscapINI into an APCu cache.
Nothing is written to disk and no data is shipped with the package: the converted browscap
data lives in the shared memory segment of the PHP process, under an APCu namespace derived from
the installation path (BrowscapFactory builds an
Ox\Components\Cache\Adapters\APCuAdapter).
Contains browscap factory :
$bc = \OxBrowscap\BrowscapFactory::create(); $result = $bc->getBrowser();
Public API
\OxBrowscap\BrowscapFactory exposes four static methods :
-
create(): Browscap
The read instance, bound to the APCu cache.getBrowser()throwsBrowscapPHP\Exception("there is no active cache available") when the cache holds no data. -
updateCache(bool $force = false): void
Downloads the browscap ini from browscap.org and converts it into the cache. Without$force, the remote version is checked first and nothing is rewritten when it is not newer than the cached one. With$force, thebrowscap.versionentry is deleted beforehand so that the whole data set gets rewritten. Stale entries are purged once the new data has been written. -
hasCache(): bool
Tells whether the cache currently holds usable data. Worth probing beforegetBrowser(), which throws otherwise: APCu is volatile (FPM restart, expunge, purge of a saturated segment) so a cache warmed earlier is not guaranteed to still be there. -
purgeStaleEntries(): int
Deletes thepatterns/inipartsentries belonging to a browscap version other than the one currently referenced by the cache metadata, and returns how many were deleted. No-op when that version is unknown.
Beware of the side effect of $force: the version key is dropped before the
download, so a updateCache(true) that fails (unreachable endpoint) leaves the cache
cold until the next successful run.
How to release a version ?
This only publishes the package: no browscap data is stored in the repository.
git clone project
composer update
git add .
git commit -m "XXX"
git push
git tag X.X.X
git push --tags
How to warm or refresh the browscap cache ?
Run this on the machine whose APCu cache has to be filled - it calls
BrowscapFactory::updateCache(true), which downloads the data from browscap.org and
writes it to the local shared memory only.
php src/update.php
How to tests ?
vendor/bin/phpunit -c phpunit.xml
Need help ?
vendor/bin/browscap-php list
Caveats
The cache is local to the PHP shared memory segment: it cannot be built once and distributed, it has to be warmed on every machine (and again after every restart that clears APCu). This is also why a scheduled CI job cannot prepare it - the cache of a job dies with the job.