# Reference

## `Flagship` class

The `Flagship` class represents the SDK. It facilitates the initialization process and creation of new visitors.

### `start` method

Start the flagship SDK

* **`public static function start(string $envId, string $apiKey, ?FlagshipConfig $config = null)`**

Arguments:

| Name   | Type                                                                          | Required     | Description                                                                   |
| ------ | ----------------------------------------------------------------------------- | ------------ | ----------------------------------------------------------------------------- |
| envId  | String                                                                        | **Required** | Environment id provided by Flagship.                                          |
| apiKey | String                                                                        | **Required** | Api authentication key provided by Flagship.                                  |
| config | <p>\Flagship\Config\DecisionApiConfig<br>\Flagship\Config\BucketingConfig</p> | **Optional** | Custom flagship configuration. [see SDK configuration](#flagshipconfig-class) |

Example:

```php
require __DIR__ . '/vendor/autoload.php';

use Flagship\Flagship;

Flagship::start("<ENV_ID>", "<API_KEY>");
```

\\

### `newVisitor` method

Initialize the builder for visitor creation, and Return a [`VisitorBuilder`](#visitorbuilder) instance.

* **`public static function newVisitor(string $visitorId, bool $hasConsented) : \Flagship\Visitor\VisitorBuilder`**

Arguments:

| Name         | Type   | Description                                                                                                                                                                                             |
| ------------ | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorId    | string | Unique visitor identifier. If `null` is given, the SDK generates one by default.                                                                                                                        |
| hasConsented | bool   | <p><strong>Required</strong><br>Specifies if the visitor has consented for personal data usage. When set to false, some features will be deactivated and the cache will be deactivated and cleared.</p> |

Example:

```php
use Flagship\Flagship;

Flagship::start("<ENV_ID>", "<API_KEY>");

$visitor = Flagship::newVisitor("your_visitor_id")
              ->withContext(["age" => 31, "isVip" => true])
              ->build();
```

\\

### `close` method

This method batches and sends all collected hits. It should be called when your application (script) is about to `terminate` or `in the event of a crash` to ensures that all collected data is sent and not lost.

* **`public static function Flagship::close(): void`**

### `getConfig` method

Return the current config used by the SDK. [see configuration](#flagshipconfig-class)

* **`public static function Flagship::getConfig(): FlagshipConfig`**

### `getStatus` method

Return current status of Flagship SDK.

* **`public static function Flagship::getStatus(): FSSdkStatus`**

List of possible `Flagship\Enum\FSSdkStatus`:

| Status                             | type | value | Description                                                                                                             |
| ---------------------------------- | ---- | ----- | ----------------------------------------------------------------------------------------------------------------------- |
| FSSdkStatus::SDK\_NOT\_INITIALIZED | int  | 0     | It is the default initial status. This status remains until the sdk has been initialized successfully.                  |
| FSSdkStatus::SDK\_INITIALIZING     | int  | 1     | The SDK is currently initializing.                                                                                      |
| FSSdkStatus::SDK\_PANIC            | int  | 2     | Flagship SDK is ready but is running in Panic mode: All features are disabled except the one which refresh this status. |
| FSSdkStatus::SDK\_INITIALIZED      | int  | 3     | The Initialization is done, and Flagship SDK is ready to use.                                                           |

\\

## `FlagshipConfig` class

This class represents the configuration for the Flagship SDK. It provides methods to set and retrieve various configuration options.

### `decisionApi` method

Initialize the SDK to start in Decision-Api mode

When the SDK is running in `DecisionApi` mode, the campaign assignments and targeting validation take place server-side in the flagship infrastructure. In this mode, each call to the [`fetchFlags`](#fetchflags-method) method to refresh the flags will make an HTTP request.

* **`public static function FlagshipConfig::decisionApi() : Flagship\Config\DecisionApiConfig`**

Example:

```php
//Start sdk in Decision api mode.

use Flagship\Flagship;
use Flagship\Config\FlagshipConfig;

$config = FlagshipConfig::decisionApi();

Flagship::start("<ENV_ID>", "<API_KEY>", $config);
```

### `bucketing` method

Initialize the SDK to start in Bucketing-mode

In `Bucketing` mode, when `fetchFlags` method is called. The SDK will check the `bucketing file` fetched through [**flagship-sync-agent endpoint URL**](#bucketing-polling) . Then validates campaigns targeting the visitor and assigns a variation. [**Learn more**](https://github.com/flagship-io/Gitbook/blob/main/docs/bucketing/README.md)

In order to feed `bucketing file`, you must run bucketing polling process. **See**[**Bucketing polling**](#bucketing-polling) **section**.

* **`public static function FlagshipConfig::bucketing(string $syncAgentUrl) : Flagship\Config\BucketingConfig`**

Arguments:

| Name         | Type   | Description                                                                            |
| ------------ | ------ | -------------------------------------------------------------------------------------- |
| syncAgentUrl | string | [flagship-sync-agent](https://github.com/flagship-io/flagship-sync-agent) endpoint URL |

Example:

```php
//Start sdk in Bucketing mode.

use Flagship\Flagship;
use Flagship\Config\FlagshipConfig;

$config = FlagshipConfig::bucketing("http://127.0.0.1:8080/bucketing");

Flagship::start("<ENV_ID>", "<API_KEY>", $config);
```

### `setCacheStrategy` accessor

Define the strategy that will be used for hit batching with tracking manager.

The SDK allows you to send hits with a batching system. The advantage of batch processing with the TrackingManager is to use less network traffic, avoid loss of hits with cache, and catch all hits that would failed and resend them.

* **`public function setCacheStrategy(CacheStrategy $cacheStrategy):\Flagship\Config\FlagshipConfig`**

Argument:

| Name          | Type | Default value | Description     |
| ------------- | ---- | ------------- | --------------- |
| cacheStrategy | int  | 1             | Cache strategy. |

List of possible `Flagship\Enum\CacheStrategy` :

| Key                                                    | Type | Value | Description                                                                                                                                                                                                                                                                                                             |
| ------------------------------------------------------ | ---- | ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| CacheStrategy::BATCHING\_AND\_CACHING\_ON\_FAILURE     | int  | 1     | <p>\[<strong>Recommended</strong>] When a hit is emitted, it will first be added into the pool, then batched and sent when the method <code>Flagship::close()</code> is invoked. If the batch send failed, all hits inside will be cached in database using IHitCacheImplementation.<br><br>see example using redis</p> |
| CacheStrategy::NO\_BATCHING\_AND\_CACHING\_ON\_FAILURE | int  | 2     | <p>When a hit is emitted, it will be sent directly. If the hit sending failed, it will be cached in database using IHitCacheImplementation.<br><br>Hits are sent as they are emitted.<br><br>This strategy uses a little more network traffic than the first because each hit emitted will send an HTTP request.</p>    |

{% hint style="info" %}
📘 Information

Whenever your application (script) is about to `terminate` or `in the event of a crash`, you should call the [`Flagship::close()`](#close-function) method to ensures that all the collected data is sent and not lost.
{% endhint %}

Example

```php
use Flagship\Config\FlagshipConfig;
use Flagship\Enum\CacheStrategy;

$config = FlagshipConfig::decisionApi()
    ->setCacheStrategy(CacheStrategy::BATCHING_AND_CACHING_ON_FAILURE);

Flagship::start("<ENV_ID>", "<API_KEY>", $config);

//Create visitor
//Get your flag 
//Send your hits
//Do your stuff 

//Call before terminating 
Flagship::close();
```

### `setLogManager` accessor

Specify a custom implementation of LogManager in order to receive logs from the SDK.

* **`public function setLogManager(Psr\Log\LoggerInterface $logManager) : Flagship\Config\FlagshipConfig`**

Argument:

| Name       | Type                    | Description                          |
| ---------- | ----------------------- | ------------------------------------ |
| logManager | Psr\Log\LoggerInterface | Custom implementation of LogManager. |

### `setLogLevel` accessor

This accessor specifies the maximum log level to display..

* **`public function setLogLevel(LogLevel $logLevel) : \Flagship\Config\FlagshipConfig`**

Argument:

| Name  | Type | Description                                           |
| ----- | ---- | ----------------------------------------------------- |
| level | int  | Value from `0` to `9` check `\Flagship\Enum\LogLevel` |

Here are the logs informations you'll have for each levels `Flagship\\Enum\\LogLevel`

| Key                 | Value | Type | Description                               |
| ------------------- | ----- | ---- | ----------------------------------------- |
| LogLevel::NONE      | 0     | int  | Logging will be disabled.                 |
| LogLevel::EMERGENCY | 1     | int  | Only emergencies will be logged           |
| LogLevel::ALERT     | 2     | int  | Only alerts and above will be logged.     |
| LogLevel::CRITICAL  | 3     | int  | Only critical and above will be logged.   |
| LogLevel::ERROR     | 4     | int  | Only errors and above will be logged.     |
| LogLevel::WARNING   | 5     | int  | Only warnings and above will be logged.   |
| LogLevel::NOTICE    | 6     | int  | Only notices and above will be logged.    |
| LogLevel::INFO      | 7     | int  | Only info logs and above will be logged.  |
| LogLevel::DEBUG     | 8     | int  | Only debug logs and above will be logged. |
| LogLevel::ALL       | 9     | int  | Everything will be logged.                |

### `setTimeout` accessor

Specify timeout in millisecond for api request.

* **`public function setTimeout(int $timeout) : \Flagship\Config\FlagshipConfig`**

Argument:

| Name    | Type | Description                              |
| ------- | ---- | ---------------------------------------- |
| timeout | int  | Time in milliseconds. Default is 2000ms. |

### `setFetchThirdPartyData` accessor (**Bucketing mode only**)

If true, the SDK will fetch the visitor's segment from the [universal data connector](https://developers.abtasty.com/docs/data/universal-data-connector) each time `fetchFlags` is called and append those segments in the visitor context.

* **`public function setFetchThirdPartyData(bool $fetchThirdPartyData): \Flagship\Config\FlagshipConfig`**

Argument:

| Name                | Type | Default | Description |
| ------------------- | ---- | ------- | ----------- |
| fetchThirdPartyData | bool | false   | value       |

### `setOnVisitorExposed` accessor

Specify a callback function to be called each time a flag has been exposed to a visitor (i.e., when an activation hit is sent by the SDK).

* **`public function setOnVisitorExposed(callable $onVisitorExposed) \Flagship\Config\FlagshipConfig`**

Argument:

| Name             | Type     | Description                                                                                                                                                   |
| ---------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| onVisitorExposed | callable | Callback to trigger when a Flag has been exposed to a visitor and succeed. It is triggered with 2 arguments: ExposedVisitorInterface and ExposedFlagInterface |

Here is an example on how to use this callback:

[Example with Mixpanel integration](/server-side/integrations/analytics/integrate-with-mixpanel.md)\
[Example with Segment integration](/server-side/integrations/analytics/integrate-with-segmentcom.md)

### `setOnSdkStatusChanged` accessor

Define a callable function to get callback when the SDK status has changed. **See** [**SDK status**](#getstatus-method) **section**.

* **`public function setOnSdkStatusChanged(callable $onSdkStatusChanged) \Flagship\Config\FlagshipConfig`**

Argument:

| Name               | Type     | Description                                      |
| ------------------ | -------- | ------------------------------------------------ |
| onSdkStatusChanged | callable | Callback to trigger when SDK status has changed. |

### `setVisitorCacheImplementation` accessor

Define an object that implement the interface IVisitorCacheImplementation to handle the visitor cache.\
[see cache-manager](#cache-management)

* **`public function setVisitorCacheImplementation(IVisitorCacheImplementation $visitorCacheImplementation) : \Flagship\Config\FlagshipConfig`**

Argument:

| Name                       | Type                                       | Description                                                                        |
| -------------------------- | ------------------------------------------ | ---------------------------------------------------------------------------------- |
| visitorCacheImplementation | Flagship\Cache\IVisitorCacheImplementation | implementation of [IVisitorCacheImplementation](#managing-visitor-cache) interface |

### `setHitCacheImplementation` accessor

Define an object that implement the interface IHitCacheImplementation to handle hits cache.\
[see cache-manager](#cache-management)

* **`public function setHitCacheImplementation(IHitCacheImplementation $hitCacheImplementation) : \Flagship\Config\FlagshipConfig`**

Argument:

| Name                   | Type                                   | Description                                                                    |
| ---------------------- | -------------------------------------- | ------------------------------------------------------------------------------ |
| hitCacheImplementation | Flagship\Cache\IHitCacheImplementation | implementation of [IHitCacheImplementation](#managing-visitor-cache) interface |

### `setDisableDeveloperUsageTracking` accessor

Determines whether to disable the collection of analytics data.

* **`public function setDisableDeveloperUsageTracking(bool $disableDeveloperUsageTracking ): \Flagship\Config\FlagshipConfig`**

Argument:

| Name                          | Type | Default value | Description                                 |
| ----------------------------- | ---- | ------------- | ------------------------------------------- |
| disableDeveloperUsageTracking | bool | false         | if set true no usage data will be collected |

### `setSyncAgentUrl` accessor (**Bucketing mode only**)

Define the [flagship-sync-agent](https://github.com/flagship-io/flagship-sync-agent) endpoint URL where the SDK will fetch the bucketing file from polling process

* **`public function setBucketingUrl(string $syncAgentUrl): \Flagship\Config\BucketingConfig`**

| Name         | Type   | Description                      |
| ------------ | ------ | -------------------------------- |
| syncAgentUrl | string | flagship-sync-agent endpoint URL |

\\

## `VisitorBuilder` class

`\Flagship\Visitor\VisitorBuilder` is a fluent interface builder api managing Visitor creation.

### `setIsAuthenticated` method

Specify whether the Visitor is authenticated or anonymous.

* **`public function isAuthenticated(bool $isAuthenticated) : \Flagship\Visitor\VisitorBuilder`**

Argument:

| Name            | Type | Description                                                        |
| --------------- | ---- | ------------------------------------------------------------------ |
| isAuthenticated | bool | true for an authenticated visitor, false for an anonymous visitor. |

### `setContext` method

Specify Visitor initial context key / values used for targeting.

* **`public function setContext(array $context) : \Flagship\Visitor\VisitorBuilder`**

Argument:

| Name        | Type                      | Description                                                                                                                                                                                                                                                                                                                                                                       |
| ----------- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| withContext | array (associative array) | <p>Visitor initial context.<br>e.g: <code>\["age"=>42, "IsVip"=>true, "country"=>"UK"]</code>. <strong>Note:</strong><br>• Visitor context keys must have a type of <code>string</code><br>• Visitor context values must have a type of <code>string</code>, <code>bool</code>, <code>numeric</code><br>• Visitor context keys and values are <strong>case sensitive</strong></p> |

### `setOnFetchFlagsStatusChanged` method

Specify a callback function to be called when the status of the fetchFlags method changes.

* **`public function onFetchFlagsStatusChanged(callable $onFetchFlagsStatusChanged): \Flagship\Visitor\VisitorBuilder`**

Argument:

| Name                      | Type     | Description                                                                                                                                                                                                |
| ------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| onFetchFlagsStatusChanged | callable | <p>Function callback.<br>The callback function should have the following signature:<br><code>function(FetchFlagsStatusInterface $fetchFlagsStatus): void</code>.<br>See the FetchFlagsStatusInterface.</p> |

### `build` method

It completes the Visitor Creation process and returns an instance of [`\Flagship\Visitor\VisitorInterface`](#visitor)

* **`public function build() : \Flagship\Visitor\Visitor`**

### Example

```php

use Flagship\Flagship;
use Flagship\Model\FetchFlagsStatusInterface;

$visitor = Flagship::newVisitor(null, true)
    ->setContext(["age" => 31, "isVip" => true])
    ->onFetchFlagsStatusChanged(function (FetchFlagsStatusInterface $status) {
        // 
    })->build();
```

\\

## `VisitorInterface`

The `VisitorInterface` interface represents a unique user within your application. It aids in managing the visitor's data and fetching the corresponding flags for the visitor from the [Flagship platform](https://app.flagship.io/login) .

### `getVisitorId` getter

The unique visitor identifier.

* **`public function getVisitorId() : string`**

### `getAnonymousId` getter

Visitor anonymous id

* **`public function getAnonymousId(): string`**

### `hasConsented` getter

It returns True if the visitor has consented for private data usage, otherwise return False.

* **`public function hasConsented(): boolean`**

### `setConsent` setter

Set if visitor has consented for protected data usage.

* **`public function setConsent(boolean $hasConsented): void`**

### `getContext` getter

Get the current visitor's context

* **`function getContext(): array`**

### `setContext` setter

Clear the current context and set a new context value

* **`public function setContext(array $context)`**

### `clearContext` method

Clear the visitor's context

**`public function clearContext() : void`**

### `getFetchStatus` getter

The fetch status of the flags. see the [FetchFlagsStatusInterface](#fetchflagsstatusinterface)

* **`public function getFetchStatus(): FetchFlagsStatusInterface;`**

### `getFlagsDTO` method

Return an array of all flags data fetched for the current visitor.

* **`public function getFlagsDTO(): FlagDTO[]`**

### `updateContext` method

Update the visitor context values, matching the given keys, used for targeting. If the key doesn't exist in the visitor's context, it will be added.

* **`public function updateContext(string $key, bool|numeric|string $value) : void`**

Arguments:

| Name  | Type                      | Description                                                                                                                                                                                                                             |
| ----- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| key   | String                    | <p>Context key.<br><strong>Note:</strong><br>• Visitor context keys must have a type of <code>string</code>.</p>                                                                                                                        |
| value | bool or numeric or string | <p>Context value.<br><strong>Note:</strong><br>• Visitor context values must have a type of <code>string</code>, <code>bool</code>, <code>numeric</code>.<br>• Visitor context keys and values are <strong>case sensitive</strong>.</p> |

### `updateContextCollection` method

Update the visitor context values, matching the given keys, used for targeting. If the key doesn't exist in the visitor's context, it will be added.

* **`public function updateContextCollection(array $Context) : void`**

Argument:

| Name    | Type                      | Description                                                                                                                                                                                                                                                                                                                                                                                |
| ------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| context | array (associative array) | <p>Collection of keys and values. e.g: <code>\["age"=>42, "IsVip"=>true, "country"=>"UK"]</code>.<br><strong>Note:</strong><br>• Visitor context keys must have a type of <code>string</code>.<br>• Visitor context values must have a type of <code>string</code>, <code>bool</code>, <code>numeric</code>.<br>• Visitor context keys and values are <strong>case sensitive</strong>.</p> |

#### Context with predefined keys of context

Here's an example of how to use these predefined keys to update the visitor context in both Node.js and Deno environments:

```php
use Flagship\Flagship;
use Flagship\Enum\FlagshipContext;

Flagship::start("<ENV_ID>", "<API_KEY>");
$visitor = Flagship::newVisitor("your_visitor_id", true)
              ->context(["age" => 31, "isVip" => true])
              ->build();

$visitor->updateContext(FlagshipContext::OS_NAME, "linux");
$visitor->updateContext(FlagshipContext::IP, "127.0.0.1");
```

[Here](#predefined-visitor-context-keys) is the List of all predefined context keys.

### `fetchFlags` method

Invokes the `decision API` or refers to the `bucketing file` to refresh all campaign flags based on the visitor's context.

* **`public function fetchFlags() : void`**

Example:

```php
use Flagship\Flagship;

Flagship::start("<ENV_ID>", "<API_KEY>");

$visitor = Flagship::newVisitor("your_visitor_id", true)->build();

$visitor->fetchFlags();
```

### `getFlag` method

Returns an instance of [FlagInterface](#flaginterface) by its key. If no flag matches the given key, an empty flag will be returned. the `exists()` method of the [FlagInterface](#flaginterface) object can be called to check if the flag has been found.

* **`public function getFlag(string $key) : \Flagship\Flag\FlagInterface`**

| Argument | Type   | Description                |
| -------- | ------ | -------------------------- |
| key      | string | Key associated to the flag |

Example:

```php
use Flagship\Flagship;

Flagship::start("<ENV_ID>", "<API_KEY>");

$visitor = Flagship::newVisitor("your_visitor_id", true)->build();

$visitor->fetchFlags();

$flag = $visitor->getFlag("displayVipFeature");
```

### `authenticate` method

Authenticates anonymous visitor

* **`public function authenticate(string $visitorId) : void`**

| Parameter | Type   | Description                          |
| --------- | ------ | ------------------------------------ |
| visitorId | string | Id of the new authenticated visitor. |

{% hint style="info" %}
📘 Information

* It is recommended calling the [**fetchFlags**](#fetchflags) method just after authenticating a visitor as the visitor data has changed.
* The visitor targeting / Flags could change based on this new data.
  {% endhint %}

### `unauthenticate` method

This method changes authenticated Visitor to anonymous visitor.

* **`public function unauthenticate() : void`**

{% hint style="info" %}
📘 Information

* It is recommended calling the [**fetchFlags**](#fetchflags) method just after authenticating a visitor as the visitor data has changed.
* The visitor targeting / Flags could change based on this new data.
  {% endhint %}

### `sendHit` method

This method sends Hits to the Flagship servers for reporting.

* **`public function sendHit(HitAbstract $hit) : void`**

| Parameter | Type        | Description  |
| --------- | ----------- | ------------ |
| hit       | HitAbstract | Hit to send. |

Example:

```php
use Flagship\Flagship;
use Flagship\Hit\Page;

$visitor = Flagship::newVisitor("your_visitor_id", true)->build();

$visitor->sendHit(new Page("https://www.my_domain_com/my_page"));
```

\\

## `FlagInterface`

This interface represents a flag in the `Flagship SDK`. It helps you retrieve the flag value, access flag metadata, expose the flag, verify the flag's existence, and get the flag status with the following API:

### `getValue` method

Returns the value of the flag if the flag exists and the type of the default value matches the flag type value, otherwise it returns the default value.

* **`public function getValue(bool $visitorExposed, bool|numeric|string|null|array $defaultValue) : bool|numeric|string|null|array`**

Argument:

| Name           | Type                                       | Default Value | Description                                                                                                                                                                                                                                                                                                                 |
| -------------- | ------------------------------------------ | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| defaultValue   | bool \| numeric \| string \| array \| null | Required      | <p>Flag default value.<br><br>Default value must be one of the following types: <code>string</code>, <code>bool</code>, <code>numeric</code>, <code>array</code>, or <code>null</code>.</p>                                                                                                                                 |
| visitorExposed | bool                                       | true          | <p>Indicates to Flagship that the visitor has been exposed and has seen this flag. This will increment the visits for the current variation on your campaign reporting.<br>It is possible to set this param to <code>false</code> and call the <code>visitorExposed()</code> method afterward when the visitor sees it.</p> |

Example:

```php
use Flagship\Flagship;

Flagship::start("<ENV_ID>", "<API_KEY>");

$visitor = Flagship::newVisitor("your_visitor_id", true)->build();

$visitor->fetchFlags();

$flagValue = $visitor->getFlag("displayVipFeature")->getValue(false);
```

### `getMetadata` method

Returns the campaign information metadata, an empty object if the Flag doesn't exist, or if the default value type does not correspond to the Flag type in Flagship.

* **`public function getMetadata() : FlagMetadata`**

The `FlagMetadata` class has the following shape:

| getters               | Type    | Description                              |
| --------------------- | ------- | ---------------------------------------- |
| getCampaignId         | string  | Campaign ID                              |
| getCampaignName       | string  | Campaign name                            |
| getVariationGroupId   | string  | Variation group ID                       |
| getVariationGroupName | string  | Variation group name                     |
| getVariationId        | string  | The variation ID assigned to the visitor |
| getVariationName      | string  | Variation name                           |
| getIsReference        | boolean | Specify if its the reference variation   |
| getCampaignType       | string  | campaign type                            |
| getSlug               | string  | campaign slug                            |

### `visitorExposed` method

Notifies Flagship that the visitor has been exposed to and seen this flag.

* **`public function visitorExposed() : void`**

### `exists` method

This method checks if the flag exists.

* **`public function exists() : bool`**

### `getStatus` method

Returns the status of the flag.

* **`public function getStatus(): FSFlagStatus`**

List of possible `Flagship\Enum\FSFlagStatus`:

| Status                        | type | value | Description                                                                                                     |
| ----------------------------- | ---- | ----- | --------------------------------------------------------------------------------------------------------------- |
| FSFlagStatus::FETCHED         | int  | 0     | The flags have been successfully fetched from the API or re-evaluated in bucketing mode.                        |
| FSFlagStatus::FETCH\_REQUIRED | int  | 1     | The flags need to be re-fetched due to a change in context, or because the flags were loaded from cache or XPC. |
| FSFlagStatus::NOT\_FOUND      | int  | 2     | The flag was not found or do not exist.                                                                         |
| FSFlagStatus::PANIC           | int  | 3     | The SDK is in PANIC mode: All features are disabled except for the one to fetch flags.                          |

\\

## FSFlagCollectionInterface

It represents a collection of flags.

### `getSize` method

Gets the number of flags in the collection.

* **`public function getSize(): int`**

### `get` method

It returns the [flag](#flaginterface) associated with the specified key, or an empty if the key is not found.

* **`public function get(string $key): FSFlagInterface`**

Arguments:

| Name | Type   | Description                     |
| ---- | ------ | ------------------------------- |
| key  | String | The key associated to the flag. |

### `has` method

Checks if the collection contains a flag with the specified key.

* **`public function has(string $key): bool`**

Arguments:

| Name | Type   | Description                     |
| ---- | ------ | ------------------------------- |
| key  | String | The key associated to the flag. |

### `keys` method

Gets the keys of all flags in the collection.

* **`public function keys(): array`**

### `filter` method

It filters the collection based on a predicate function and returns A new [FSFlagCollectionInterface](#fsflagcollectioninterface) containing the flags that satisfy the predicate.

* **`public function filter(callable $predicate): FSFlagCollectionInterface`**

Arguments:

| Name      | Type     | Description                                                                                                                                                                                                                                                                                    |
| --------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| predicate | function | <p>A function that accepts three parameters:<br><br>\* FSFlagInterface <code>$flag</code> – The current flag being processed.<br>\* <code>string $key</code> – The key of the current flag.<br>\* <code>FSFlagCollectionInterface $collection</code> – The collection the flag belongs to.</p> |

### `exposeAll` method

Exposes all flags in the collection.

* **`public function exposeAll(): void`**

### `getMetadata` method

Retrieves the [metadata](#getMetadata-method) for all [flags](#flaginterface) in the collection.

* **`public function getMetadata(): array`**

### `toJSON` method

Serializes the [metadata](#getMetadata-method) for all flags in the collection.

* **`public function toJSON(): string`**

### `each` method

Iterates over each flag in the collection.

Arguments:

| Name      | Type     | Description                                                                                                                                                                                                                                                                                                   |
| --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| predicate | function | <p>A function that accepts three parameters:<br></p><ul><li>FSFlagInterface <code>$flag</code> – The current flag being processed.</li><li><code>string $key</code> – The key of the current flag.</li><li>FSFlagCollectionInterface <code>$collection</code> – The collection the flag belongs to.</li></ul> |

\\

## Hit Tracking

This section guides you on how to track visitors in your application and learn how to build hits to feed your reports. For more details about our measurement protocol, refer to our [Universal Collect documentation](/server-side/concepts/universal-collect-1.md).

There are five different types of Hits:

* Page
* Screen
* Transaction
* Item
* Event

### Common Optional Parameters for Hits

```php
use Flagship\Flagship;
use Flagship\Hit\Page;

$visitor = Flagship::newVisitor("your_visitor_id")->build();

$visitor->sendHit(new Page("https://www.my_domain_com/my_page")
          ->setUserIp("127.0.0.1")
          ->setScreenResolution("800X600")
          ->setLocale("fr")
          ->setSessionNumber("12345")
          );
```

| Builder Parameter   | Type   | Description        |
| ------------------- | ------ | ------------------ |
| setUserIp           | String | Visitor IP         |
| setScreenResolution | string | Screen resolution. |
| setLocale           | String | visitor language   |
| setSessionNumber    | string | Session number     |

### Page hit

This hit should be sent each time a visitor navigates to a new page.

Constructor:

**`new Page(string $pageUrl)`**

Arguments:

| Name    | Type   | Description |
| ------- | ------ | ----------- |
| pageUrl | String | Valid url.  |

Example:

```php
use Flagship\Hit\Page;

$page = new Page("https://www.my_domain_com/my_page");

$visitor->sendHit($page);
```

### Transaction hit

This hit should be sent when a visitor completes a Transaction.

Constructor:

**`new Transaction(string $transactionId, string $affiliation)`**

Arguments:

| Name          | Type   | Description                                                                                                  |
| ------------- | ------ | ------------------------------------------------------------------------------------------------------------ |
| transactionId | String | Unique identifier for your transaction.                                                                      |
| affiliation   | String | The name of the KPI that you will have inside your reporting. [**Learn more**](/server-side/glossary.md#kpi) |

A hit of type `TRANSACTION` has this following structure:

| Builder Parameter | Type   | Description                                                                                                             |
| ----------------- | ------ | ----------------------------------------------------------------------------------------------------------------------- |
| setTotalRevenue   | float  | Specifies the total revenue associated with the transaction. This value should include any shipping and/or tax amounts. |
| setShippingCosts  | float  | The total shipping cost of your transaction.                                                                            |
| setShippingMethod | String | The shipping method for your transaction.                                                                               |
| setTaxes          | float  | Specifies the total amount of taxes in your transaction.                                                                |
| setCurrency       | String | Specifies the currency of your transaction. NOTE: This value should be a valid ISO 4217 currency code.                  |
| setPaymentMethod  | String | Specifies the payment method used for your transaction.                                                                 |
| setItemCount      | int    | Specifies the number of items in your transaction.                                                                      |
| setCouponCode     | String | Specifies the coupon code used by the customer in your transaction.                                                     |

Example:

```php
use Flagship\Hit\Transaction;

$transaction = (new Transaction("#12345", "affiliation"))
            ->setCouponCode("code")
            ->setCurrency("EUR")
            ->setItemCount(1)
            ->setPaymentMethod("creditCard")
            ->setShippingCosts(9.99)
            ->setTaxes(19.99)
            ->setTotalRevenue(199.99)
            ->setShippingMethod("1day");

$visitor->sendHit($transaction);
```

### Item hit

This hit is used to associate an item with a transaction. It should be sent following the corresponding transaction hit.

Constructor:

**`new Item(string $transactionId, string $productName, string $productSku)`**

Arguments:

| Name          | Type   | Description                             |
| ------------- | ------ | --------------------------------------- |
| transactionId | String | Unique identifier for your transaction. |
| productName   | String | Name of your item.                      |
| productSku    | String | Specifies the SKU or item code.         |

A hit of type `ITEM` has this following structure:

| Builder Parameter | Type   | Description                                      |
| ----------------- | ------ | ------------------------------------------------ |
| setItemCategory   | String | Specifies the category that the item belongs to. |
| setItemPrice      | float  | Specifies the price for a single item/unit.      |
| setItemQuantity   | int    | Specifies the number of items purchased.         |

Example:

```php
use Flagship\Hit\Item;

$item = (new Item("#12345", "product", "sku123"))
            ->setItemCategory("test")
            ->setItemPrice(199.99)
            ->setItemQuantity(1);

$visitor->sendHit($item);
```

{% hint style="info" %}
📘 Information

The `Item` hit is not currently available in the Flagship reporting view.
{% endhint %}

### Event hit

This hit can be used to track any event, such as a click on 'Add To Cart' or a newsletter subscription.

**`public Event(EventCategory category, String action)`**

Argument:

| Name     | Type          | Description                                                                                                                                                                    |
| -------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| category | EventCategory | Specifies the category of your event. NOTE: This value must be either **`Flagship\Enum\EventCategory::ACTION_TRACKING`** or **`Flagship\EnumEventCategory::USER_ENGAGEMENT`**. |
| action   | String        | Event name that will also serve as the KPI that you will have inside your reporting. [**Learn more**](doc:glossary#kpi)                                                        |

An `EVENT` type hit has the following structure:

| Builder Parameter | Type    | Description                                                                                                                                                                                  |
| ----------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| setLabel          | String  | (optional) Additional description of your event.                                                                                                                                             |
| setValue          | Integer | <p>(optional) Can be used to evaluate visitor interactions with individual site objects or content items.<br><strong>NOTE</strong>: <em>this value must be non-negative / non-float</em></p> |

Example:

```php
use Flagship\Hit\Event;

$event = (new Event(EventCategory::USER_ENGAGEMENT, "action"))
              ->setLabel("label")
              ->setValue(100);

$visitor->sendHit($event);
```

\\

## Cache management

The purpose of cache management is to address the following issues:

* **Re-allocation in bucketing mode :**

In bucketing mode and with the cache enabled, the SDK will always keep visitor in the variation to which he was allocated first, in case the customer manually changed the traffic allocation or the `dynamic allocation` feature was enabled, to avoid user experience issues. Indeed in bucketing mode the assignation is made on local devices so changing traffic allocation in the platform could authorize the visitors to see different variations.

* **Handle offline mode :**

With the cache enabled, the SDK will try to retrieve the latest visitor data (campaign assignations) from the cache.

To use the cache manager the intefaces `IVisitorCacheImplementation` must be implemented through visitorCacheImplementation property accessor of [configuration](#flagship-config).

### Visitor Cache

The visitor cache is used to store the visitor data in a database through the `IVisitorCacheImplementation` interface which defines the methods that an object must implement to manager it.

```php
<?php

namespace Flagship\Cache;

interface IVisitorCacheImplementation
{
    public function cacheVisitor($visitorId, array $data);

    public function lookupVisitor($visitorId);

    public function flushVisitor($visitorId);
}

```

#### `cacheVisitor` method

This method is invoked when the SDK needs to store visitor information in your database.

* `public function cacheVisitor($visitorId, array $data) : void`

Arguments:

| Name      | Type   | Description                                                                   |
| --------- | ------ | ----------------------------------------------------------------------------- |
| visitorId | string | visitor ID                                                                    |
| data      | array  | visitor data. The array has the follows shape [`see`](#visitor-cache-format). |

#### `lookupVisitor` method

This method is invoked when the SDK needs to retrieve visitor information associated with a specific visitor ID from your database.

It has to return an array which follows this shape [see](#visitor-cache-format).

* `public function lookupVisitor($visitorId) : array`

Argument :

| Name      | Type   | Description |
| --------- | ------ | ----------- |
| visitorId | string | visitor ID  |

#### `flushVisitor` method

This method is invoked when the SDK needs to delete the visitor information associated with a specific visitor ID from your database.

It will be called every time [`setConsent`](#setconsent-setter) get false.

* `public function flushVisitor($visitorId) : void`

Argument :

| Name      | Type   | Description |
| --------- | ------ | ----------- |
| visitorId | string | visitor ID  |

{% hint style="info" %}
📘 Information

* `flushVisitor` method will be called every time [`setConsent`](#managing-visitor-consent) get false.
  {% endhint %}

#### Visitor Cache format

```php
[
  'Version' => 1,
  'Data' => [
    'VisitorId' => 'visitor_1',
    'AnonymousId' => NULL,
    'Consent' => true,
    'Context' => [
      'qa_getflag' => true,
      'fs_client' => '.NET',
      'fs_version' => 'V3',
    ],
    'AssignmentsHistory' => [
      'xxxxxxxxxxxxxxxxxxxx' => 'xxxxxxxxxxxxxxxxxxxx',
      'yyyyyyyyyyyyyyyyyyyy' => 'yyyyyyyyyyyyyyyyyyyy',
    ],
    'Campaigns' => [
      0 => [
        'CampaignId' => 'xxxxxxxxxxxxxxxxxxxx',
        'VariationGroupId' => 'xxxxxxxxxxxxxxxxxxxx',
        'VariationId' => 'xxxxxxxxxxxxxxxxxxxx',
        'IsReference' => false,
        'Type' => 2,
        'Activated' => false,
        'Flags' => [
          'key' => 'value',
        ],
      ],
      1 => [
        'CampaignId' => 'xxxxxxxxxxxxxxxxxxxx',
        'VariationGroupId' => 'xxxxxxxxxxxxxxxxxxxx',
        'VariationId' => 'xxxxxxxxxxxxxxxxxxxx',
        'IsReference' => false,
        'Type' => '',
        'Activated' => false,
        'Flags' => [
          'myAwesomeFeature' => 20,
        ],
      ],
    ],
  ],
]
```

#### Example

```php
<?php

require_once __DIR__ . '/vendor/autoload.php';


use Flagship\Cache\IVisitorCacheImplementation;
use Flagship\Config\FlagshipConfig;
use Flagship\Flagship;


/**
 * Implementing visitor caches with redis
 */
class VisitorCacheRedis implements IVisitorCacheImplementation{

    private $redis;
    public function __construct($address, $port)
    {
        $this->redis = new Redis();
        $this->redis->connect($address, $port);
    }

    public function cacheVisitor($visitorId, array $data)
    {
        $this->redis->set($visitorId, json_encode($data, JSON_NUMERIC_CHECK));
    }

    public function lookupVisitor($visitorId)
    {
        $data = $this->redis->get($visitorId);
        if (!$data){
            return null;
        }
        return json_decode($data, true);
    }

    public function flushVisitor($visitorId)
    {
      $this->redis->del($visitorId);
    }
}

Flagship::start("<ENV_ID>", "<API_KEY>",
    FlagshipConfig::bucketing("http://127.0.0.1:8080/bucketing") // set the sync-agent endpoint URL
    ->setVisitorCacheImplementation(new VisitorCacheRedis("127.0.0.1", 6379)) // set visitor cache implementation 
);

$visitor = Flagship::newVisitor("visitorID")
        ->withContext(["plan"=>"enterprise"])
        ->build();

$visitor->fetchFlags();

$flag = $visitor->getFlag("your_flag_key", "default_value") ;
echo "value: ". $flag->getValue()."\n";
echo "exists: ". $flag->exists()."\n";
echo "metadata: ". json_encode($flag->getMetadata());
```

\\

### Hit Cache

The hit cache is used to store hits in your database based on the strategy used through the `IHitCacheImplementation` interface which defines the methods that an object must implement to handle it.

```php
<?php

namespace Flagship\Cache;

interface IHitCacheImplementation
{
    public function cacheHit(array $hits);

    public function lookupHits();

    public function flushHits(array $hitKeys);

    public function flushAllHits();
}

```

#### `cacheHit` method

This method will be called to cache hits depending on cache strategy used.

* **`public function cacheHit(array $hits):void`**

Argument :

| Name | Type  | Description                                                                                                                                                                                                    |
| ---- | ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| hits | array | <p>It's an associative array where:<br></p><ul><li><strong>key</strong> – a unique ID for each hit</li><li><strong>value</strong> – an array that follows the shape of type <code>HitCacheDTO</code></li></ul> |

#### `lookupHits` method

This method will be called to load all hits from your database and trying to send them again when `Flagship::close()`.

It has to return an associative array where the key is a unique ID for each hit and the value is an array which follows this shape [see](#hitCachedto).

* **`public function lookupHits():array`**

#### `flushHits` method

This method will be called to erase all hits matching the unique Hits ID from your database.

**NOTE:** It will be called every time [`setConsent`](#setconsent-function) get false to erase all hits from database for visitor who set consent to false.

* **`public function flushHits(array $hitKeys):void`**

Argument :

| Name    | Type           | Description       |
| ------- | -------------- | ----------------- |
| hitKeys | Array\<string> | Unique ID of hits |

#### `flushAllHits` function

This method will be called to erase all hits in your database without exception.

* **`public function flushAllHits():void`**

\\

#### HitCacheDTO

```php
[
    'visitorId:Guid' => [
        'version' => 1,
        'data' => [
            'visitorId' => 'visitorId',
            'anonymousId' => NULL,
            'type' => 'ACTIVATE',
            'content' => [
                'variationGroupId' => 'xxxxxxxxxxxxxxx',
                'variationId' => 'xxxxxxxxxxxxxxxx',
                'visitorId' => 'visitorId',
                'ds' => 'APP',
                'type' => 'ACTIVATE',
                'anonymousId' => NULL,
                'userIP' => NULL,
                'pageResolution' => NULL,
                'locale' => NULL,
                'sessionNumber' => NULL,
                'key' => 'visitorId:Guid',
                'createdAt' => 1676542078044,
            ],
            'time' => 1676542078045,
        ],
    ]
]
```

{% hint style="info" %}
📘 Information

* `flushHits` method will be called every time [`setConsent`](#setconsent-function) get false.
* `Hits` older than 4H will be ignored during the resending process.
  {% endhint %}

Sample implementation of IHitCacheImplementation interface using redis

```php
use Flagship\Cache\IHitCacheImplementation;

class HitCacheRedis implements IHitCacheImplementation
{

    private $redis;
    public function __construct($address, $port, $dbIndex)
    {
        $this->redis = new Redis();
        $this->redis->connect($address, $port);
        $this->redis->select($dbIndex);
    }

    /**
     * @inheritDoc
     */
    public function cacheHit(array $hits)
    {
        $redis = $this->redis->multi();
        foreach ($hits as $key => $hit) {
            $redis->set($key, json_encode($hit));
        }
        $redis->exec();
    }

    /**
     * @inheritDoc
     */
    public function lookupHits()
    {
        $keys = $this->redis->keys('*');
        $hits = $this->redis->mGet($keys);
        if (!$hits) {
            return [];
        }
        $hitsOut = [];
        foreach ($hits as $key => $hit) {
            $hitsOut[$keys[$key]] = json_decode($hit, true);
        }
        return $hitsOut;
    }

    /**
     * @inheritDoc
     */
    public function flushHits(array $hitKeys)
    {
        $this->redis->del($hitKeys);
    }

    public function flushAllHits()
    {
        $this->redis->flushDB();
    }
}
```

\\

## `ExposedVisitorInterface`

It's an interface to get information about the visitor to whom the flag has been exposed

```php
<?php

namespace Flagship\Model;

interface ExposedVisitorInterface
{
    /**
     * Visitor id
     * @return string
     */
    public function getId(): string;

    /**
     * visitor anonymous id
     * @return string|null
     */
    public function getAnonymousId(): ?string;

    /**
     * visitor context
     * @return array<string, mixed>
     */
    public function getContext(): array;
}
```

\\

## `ExposedFlagInterface`

It's an interface to get information about the flag that has been exposed.

```php
<?php

namespace Flagship\Model;

use Flagship\Flag\FSFlagMetadataInterface;

interface ExposedFlagInterface
{
    /**
     * Return the key of flag
     * @return string
     */
    public function getKey(): string;

    /**
     * Return the value of flag
     * @return float|array|bool|int|string|null
     */
    public function getValue(): float|array|bool|int|string|null;

    /**
     * Return the metadata of flag
     * @return FSFlagMetadataInterface
     */
    public function getMetadata(): FSFlagMetadataInterface;

    /**
     * Return the default value of flag
     * @return float|array|bool|int|string|null
     */
    public function getDefaultValue(): float|array|bool|int|string|null;
}
```

## `FetchFlagsStatusInterface`

It Represents the status of visitor fetch for flag data.

```php
<?php

namespace Flagship\Model;

use Flagship\Enum\FSFetchReason;
use Flagship\Enum\FSFetchStatus;

interface FetchFlagsStatusInterface
{
    /**
     * The new status of the flags fetch.
     *
     * @return FSFetchStatus
     */
    public function getStatus(): FSFetchStatus;

    /**
     * The reason for the status change
     *
     * @return FSFetchReason
     */
    public function getReason(): FSFetchReason;
}

```

List of possible `Flagship\Enum\FSFetchStatus`:

| Status                         | Type | Value | Description                                                                                                     |
| ------------------------------ | ---- | ----- | --------------------------------------------------------------------------------------------------------------- |
| FSFetchStatus::FETCHED         | int  | 0     | The flags have been successfully fetched from the API or re-evaluated in bucketing mode.                        |
| FSFetchStatus::FETCHING        | int  | 1     | The flags are currently being fetched from the API or re-evaluated in bucketing mode.                           |
| FSFetchStatus::FETCH\_REQUIRED | int  | 2     | The flags need to be re-fetched due to a change in context, or because the flags were loaded from cache or XPC. |
| FSFetchStatus::PANIC           | int  | 3     | The SDK is in PANIC mode: All features are disabled except for the one to fetch flags.                          |

List of possible `Flagship\Enum\FSFetchReason`:

| Status                                     | Type | Value | Description                                                     |
| ------------------------------------------ | ---- | ----- | --------------------------------------------------------------- |
| FSFetchReason::NONE                        | int  | 0     | Indicates that there is no specific reason for fetching flags.  |
| FSFetchReason::VISITOR\_CREATED            | int  | 1     | Indicates that the visitor has been created.                    |
| FSFetchReason::UPDATE\_CONTEXT             | int  | 2     | Indicates that a context has been updated or changed.           |
| FSFetchReason::AUTHENTICATE                | int  | 3     | Indicates that the XPC method 'authenticate' has been called.   |
| FSFetchReason::UNAUTHENTICATE              | int  | 4     | Indicates that the XPC method 'unauthenticate' has been called. |
| FSFetchReason::FETCH\_ERROR                | int  | 5     | Indicates that fetching flags has failed.                       |
| FSFetchReason::FLAGS\_FETCHED\_FROM\_CACHE | int  | 6     | Indicates that flags have been fetched from the cache.          |

\\

## Bucketing polling

To start bucketing polling, you need to run in your infrastructure [**flagship-sync-agent**](https://github.com/flagship-io/flagship-sync-agent). This binary is a local endpoint (API) that provides the bucketing file which is downloaded from flagship CDN by performing the bucketing polling process.

[**flagship-sync-agent**](https://github.com/flagship-io/flagship-sync-agent) downloads all the campaigns configurations at once in a single bucketing file and stored it in cache. It will only be downloaded again when campaign configurations are modified in the Flagship interface.

The gain of going through flagship-sync-agent is in terms of response time. once it has downloaded the bucketing file, it delivers it within a very short time to the script that requests it.

You can download it [**here**](https://github.com/flagship-io/flagship-sync-agent)

```shell
$ ./app --envId=YOUR_ENV_ID --pollingInterval=2000 --port=3000 --address=0.0.0.0
```

arguments:

| argument        | type   | description                                                            |
| --------------- | ------ | ---------------------------------------------------------------------- |
| envId           | string | Environment id provided by Flagship.                                   |
| pollingInterval | int    | Define time interval between two bucketing updates. Default is 2000ms. |
| Port            | int    | Endpoint listen port. Default is 8080                                  |
| address         | string | Address where the endpoint is served. Default is 0.0.0.0               |

### Docker

```shell
docker pull flagshipio/sync-agent

env FS_ENV_ID="YOUR_ENV_ID" docker run -p 3000:8080 -e FS_ENV_ID flagshipio/sync-agent
```

Environment variables:

| argument              | type   | description                                                            |
| --------------------- | ------ | ---------------------------------------------------------------------- |
| FS\_ENV\_ID           | string | Environment id provided by Flagship.                                   |
| FS\_POLLING\_INTERVAL | int    | Define time interval between two bucketing updates. Default is 2000ms. |
| FS\_PORT              | int    | Endpoint listen port. Default is 8080                                  |
| FS\_ADDRESS           | string | Address where the endpoint is served. Default is 0.0.0.0               |

### API docs

| route          | Description                                           |
| -------------- | ----------------------------------------------------- |
| /bucketing     | Get the Json bucketing file                           |
| /health\_check | Return http code 200 to check if the sync agent is up |

## Predefined visitor context keys

The Flagship SDK contains predefined visitor context keys.

The keys marked as **Yes** in the **Auto-set by SDK** column will be automatically set, while the ones marked as **No** need to be set by customer.

All possible predefined keys are listed below:

| SDK constant Name                     | Description                                            | Context variable name   | Type       | Auto-set by SDK | Example         |
| ------------------------------------- | ------------------------------------------------------ | ----------------------- | ---------- | --------------- | --------------- |
| FlagshipContext::DEVICE\_LOCALE       | Language of the device                                 | sdk\_deviceLanguage     | String     | No              | fra             |
| FlagshipContext::DEVICE\_TYPE         | Type of the device                                     | sdk\_deviceType         | DeviceType | No              | Mobile          |
| FlagshipContext::DEVICE\_MODEL        | Model of the device                                    | sdk\_deviceModel        | String     | No              | samsung E1200   |
| FlagshipContext::LOCATION\_CITY       | City geolocation                                       | sdk\_city               | String     | No              | toulouse        |
| FlagshipContext::LOCATION\_REGION     | Region geolocation                                     | sdk\_region             | String     | No              | occitanie       |
| FlagshipContext::LOCATION\_COUNTRY    | Country geolocation                                    | sdk\_country            | String     | No              | France          |
| FlagshipContext::LOCATION\_LAT        | Current Latitude                                       | sdk\_lat                | Double     | No              | 43.623647       |
| FlagshipContext::LOCATION\_LONG       | Current Longitude                                      | sdk\_long               | Double     | No              | 1.445397        |
| FlagshipContext::IP                   | IP of the device                                       | sdk\_ip                 | String     | No              | 127.0.0.1       |
| FlagshipContext::OS\_NAME             | Name of the OS                                         | sdk\_osName             | String     | YES             | ubuntu / centos |
| FlagshipContext::OS\_VERSION\_NAME    | Version name of the OS                                 | sdk\_osVersionName      | String     | No              | 9.0.0           |
| FlagshipContext::OS\_VERSION\_CODE    | Version code of the OS                                 | sdk\_osVersionCode      | Number     | No              | 24              |
| FlagshipContext::CARRIER\_NAME        | Name of the carrier or mobile virtual network operator | sdk\_carrierName        | String     | No              | free            |
| FlagshipContext::INTERNET\_CONNECTION | What is the internet connection                        | sdk\_internetConnection | String     | No              | 5g              |
| FlagshipContext::APP\_VERSION\_NAME   | Version name of the app                                | sdk\_versionName        | String     | No              | 1.1.2-beta      |
| FlagshipContext::APP\_VERSION\_CODE   | Version code of the app                                | sdk\_versionCode        | Number     | No              | 40              |
| FlagshipContext::INTERFACE\_NAME      | Name of the interface                                  | sdk\_interfaceName      | String     | No              | ProductPage     |
| FlagshipContext::FLAGSHIP\_CLIENT     | Flagship SDK client (Reserved)                         | fs\_client              | String     | Yes             | PHP             |
| FlagshipContext::FLAGSHIP\_VERSION    | Version of the Flagship SDK (Reserved)                 | fs\_version             | String     | Yes             | 2.0.0           |

{% hint style="info" %}
📘 Information

To overwrite the keys, use the [`updateContext`](#updatecontext-method) method
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.abtasty.com/server-side/sdks/php/php-reference.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
