Skip to content

Latest commit

 

History

History
241 lines (167 loc) · 7.95 KB

File metadata and controls

241 lines (167 loc) · 7.95 KB

Usage Guide

This guide reflects the current implementation in src/.

Basic Generation

use JOOservices\UserAgent\Service\UserAgentService;

$service = new UserAgentService();
$ua = $service->generate();

echo $ua;

Facade API

use JOOservices\UserAgent\UserAgent;

echo UserAgent::generate();
echo UserAgent::firefox()->windows()->generate();
echo UserAgent::exclude()->chrome()->generate();

// With metadata (browser, version, OS, device, locale, arch, etc.)
$result = UserAgent::generateWithMetadata();
echo $result->getUaString();
$meta = $result->getMetadata();

Exclude mode

After exclude(), every following constraint in the chain is an exclusion (disallow that value), not an inclusion. There is no “include again” in the same chain.

  • UserAgent::exclude()->mobile()->generate() → any browser/OS, but desktop or tablet only (mobile excluded).
  • UserAgent::chrome()->exclude()->mobile()->generate()Chrome on desktop or tablet (mobile excluded).
  • UserAgent::exclude()->safari()->generate() → any device/OS, but Chrome, Firefox, or Edge (Safari excluded).

Unique Mode

unique() uses JOOservices\UserAgent\Facade\UniqueGuard (in-memory static set for current PHP process).

for ($i = 0; $i < 10; $i++) {
    echo UserAgent::unique()->generate(), PHP_EOL;
}

UserAgent::resetUnique();

Profiles API

Two entry paths exist:

  1. JOOservices\UserAgent\Service\Profiles\Profiles
  2. UserAgent::profile() via JOOservices\UserAgent\Facade\ProfileBuilder
use JOOservices\UserAgent\Service\UserAgentService;
use JOOservices\UserAgent\Service\Profiles\Profiles;

$service = new UserAgentService();
$profiles = new Profiles($service);

echo $profiles->desktopChrome->windows();
echo $profiles->mobileSafari->iphone();
echo $profiles->androidChrome->phone();

GenerationSpec

use JOOservices\UserAgent\Domain\Enums\BrowserFamily;
use JOOservices\UserAgent\Domain\Enums\DeviceType;
use JOOservices\UserAgent\Domain\Enums\OperatingSystem;
use JOOservices\UserAgent\Spec\GenerationSpec;

$spec = GenerationSpec::create()
    ->browser(BrowserFamily::Chrome)
    ->device(DeviceType::Desktop)
    ->os(OperatingSystem::MacOS)
    ->versionMin(110)
    ->versionMax(130)
    ->locale('en-US')
    ->arch('x86_64')
    ->build();

$ua = $service->generate($spec);

Strategy Note

GenerationSpec::strategy() accepts class names, but UserAgentService currently has partial strategy handling:

  • default (WeightedStrategy) uses weighted selection against filtered candidates.
  • non-default strategy values currently fall back to random selection from filtered candidates.

See src/Service/UserAgentService.php for details. Strategy class names are resolved at runtime; unknown or invalid strategy classes fall back to WeightedStrategy.

Deterministic Seed

// Via service (positional or named)
$seed = 12345;
$ua1 = $service->generate(null, $seed);
$ua2 = $service->generate(spec: $spec, seed: $seed);

// Via facade: set global seed for subsequent generation
UserAgent::seed(12345);
UserAgent::chrome()->windows()->generate();

The same seed can still produce different values if constraints or call paths differ.

Scenario presets

Scenario-oriented presets return a GenerationSpec (or list of specs) for common use cases. Use with UserAgent::batch() or $service->generate($spec).

Preset Description
Modern desktop traffic Desktop only, recent versions. UserAgent::scenarioPresetModernDesktop()
Mobile-first APAC Mobile devices only. UserAgent::scenarioPresetMobileFirstApac()
Crawler-safe random rotation Fully random realistic UAs; use with unique() and generateMany(). UserAgent::scenarioPresetCrawlerSafeRotation()
QA browser matrix One spec per valid (browser, device, OS). UserAgent::scenarioPresetQaBrowserMatrix() returns GenerationSpec[]
use JOOservices\UserAgent\UserAgent;
use JOOservices\UserAgent\Service\ScenarioPresets;

$spec = UserAgent::scenarioPresetModernDesktop();
$ua = UserAgent::batch(1, ['spec' => $spec])->getResults()[0];

// Or use the class directly
$spec = ScenarioPresets::qaBrowserMatrixSampleSet();

Batch API with metadata and summary

UserAgent::batch($count, $options) generates N UAs with optional dedupe, metadata, and summary.

Options: unique (bool), withMetadata (bool), summary (bool), spec (GenerationSpec|null).

$result = UserAgent::batch(10, ['unique' => true, 'withMetadata' => true, 'summary' => true]);
$list = $result->getResults(); // array of {ua, metadata}
$summary = $result->getSummary(); // ['byBrowser' => [...], 'byOs' => [...]]

Batch + chain (same constraints, N UAs)

To generate N UAs that all satisfy the same fluent constraints (with random browser/device/OS within those constraints each time), use the builder’s generateMany():

// 5 UAs, each Chrome on Windows (version/locale/arch vary)
$list = UserAgent::chrome()->windows()->generateMany(5);

// With unique guarantee and metadata
$builder = UserAgent::chrome()->windows()->unique();
$results = $builder->generateManyWithMetadata(10, unique: true);

To generate N UAs from a single resolved spec (one fixed browser/device/OS, only version/locale/arch vary), resolve the chain once with toSpec() and pass to batch():

$spec = UserAgent::chrome()->windows()->toSpec();
$result = UserAgent::batch(5, ['spec' => $spec, 'unique' => true]);

Bot generation

Bot User-Agent strings are produced by BotUserAgentService and exposed via the facade:

echo UserAgent::googlebot();           // desktop-style
echo UserAgent::googlebot(mobile: true);
echo UserAgent::bingbot();
echo UserAgent::bot(BotType::Yandexbot, mobile: true);

Valid combinations

Before generating, you can query which (browser, device, OS) combinations are valid:

use JOOservices\UserAgent\Domain\Enums\BrowserFamily;
use JOOservices\UserAgent\Domain\Enums\DeviceType;
use JOOservices\UserAgent\Domain\Enums\OperatingSystem;

$supported = UserAgent::supportedCombinations();
$valid = $supported->getValidCombinations(); // list of ValidCombination
$supported->isValid(BrowserFamily::Safari, DeviceType::Desktop, OperatingSystem::Windows); // false

CLI

Entrypoint: bin/useragent (or ./vendor/bin/useragent when installed via Composer). Implementation: src/Console/ConsoleApp.php with CliArgParser, CliSpecFactory, and CliOutputFormatter.

./bin/useragent --count=5 --browser=firefox
./bin/useragent --bot=googlebot --mobile
./bin/useragent --count=3 --format=json --unique
./bin/useragent --examples   # show usage examples
./bin/useragent --help       # show help

Supported options: browser, device, os, bot, count, format (text|json|csv), unique, mobile (for bot mode), examples, help.

Use-case recipes

  • Generate 100 unique mobile UAs for scraper rotation

    UserAgent::mobile()->unique() then loop 100x ->generate(), or
    UserAgent::batch(100, ['spec' => UserAgent::scenarioPresetMobileFirstApac(), 'unique' => true])

  • Deterministic UA for PHPUnit

    UserAgent::seed(12345); then UserAgent::chrome()->windows()->generate(); or
    $service->generate($spec, seed: 12345)

  • Exclude Safari

    UserAgent::exclude()->safari()->generate() (see Exclude mode for how exclude works)

  • Simulate weighted real-market traffic

    Default builder uses weighted strategy: UserAgent::generate() or
    UserAgent::batch(N, ['unique' => false])

  • Browser matrix for QA

    $specs = UserAgent::scenarioPresetQaBrowserMatrix(); then for each spec
    $service->generate($spec) or batch with each spec.

See Also