> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kameleoon.com/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK de PHP

> Integre el SDK de PHP de Kameleoon para ejecutar experimentos y activar feature flags en servidores back-end PHP, con seguimiento opcional mediante cron job.

Con el SDK de PHP de Kameleoon, puede ejecutar experimentos y activar feature flags en su servidor PHP de back-end. Es sencillo integrar nuestro SDK en su aplicación web y su huella (memoria y uso de red) es baja.

**Primeros pasos**: Para obtener ayuda para comenzar, consulte la [guía del desarrollador](#guía-del-desarrollador).

**Changelog**: Última versión del SDK de PHP: 4.23.0 [Changelog](https://github.com/Kameleoon/client-php/blob/master/CHANGELOG.md).

**Métodos del SDK**: Para la documentación de referencia completa del SDK de PHP, consulte la sección [referencia](#referencia).

## Guía del desarrollador

This guide is designed to help you integrate our SDK into your application code.

### Primeros pasos

Primero debe instalar nuestro SDK. Una vez descomprimido, verá dos directorios: **kameleoon/** y **job/**.

#### Instalación del cliente PHP (Composer package)

<Warning>
  Please carefully read the sections on [installing the cron job](#installing-the-cron-job) and [using the PHP SDK without a cron job](#using-the-php-sdk-without-a-cron-job).
</Warning>

El paquete de instalación está disponible en [Packagist](https://packagist.org/packages/kameleoon/kameleoon-client-php). Puede instalar el SDK de PHP añadiéndolo como dependencia mediante Composer:

```json title="composer.json" theme={null}
{
  "require": {
    "kameleoon/kameleoon-client-php": "^4.18.0"
  }
}
```

Finally, execute the following command to regenerate the autoloader:

```bash theme={null}
composer install
```

#### With a cron job (Recommended)

<Tip>
  Setting up the cron allows the tracking of data added by the PHP sdk with the [addData()](#adddata) method. However, if you are unable to install it, front end tracking can still be implemented following [this guide](#without-a-cron-job).
</Tip>

El directorio **job/** corresponde a un trabajo que debe ejecutarse mediante un planificador de tareas estándar (como cron).
Le sugerimos instalar el script en `/usr/local/opt/kameleoon/kameleoon-client-php-process-queries.sh` y usar nuestra entrada de crontab predeterminada. Sin embargo, puede instalarlo en otra ubicación y modificar la entrada de crontab en consecuencia.

##### Without a cron job

If you cannot install the cron job, you can use Kameleoon in [hybrid mode](/developer-docs/feature-experimentation/get-started/hybrid-experimentation) to benefit from the Kameleoon Application Engine's, `engine.js` (previously named, `kameleoon.js`) tracking capabilities. Our SDK provides the [`getEngineTrackingCode()`](#getenginetrackingcode) method, which sends exposure events to Kameleoon or any other analytics solution you use on your website.

<Warning>
  With this approach **you won't be able to track data** added with the [addData()](#adddata) method of the PHP SDK.
  In other words, the **only** way for the PHP SDK to collect and process experiment data server-side is through the **cron job**.
  The hybrid mode is useful for tracking purposes, but **does not enable backend data collection**.
</Warning>

#### Configuración adicional

You can customize the behavior of the PHP SDK via a configuration file. We provide a sample configuration file named `client-php.json.sample` in the SDK archive. You can also [download a sample configuration](/assets/developer-docs/sdks/web-sdks/client-configs/client-php.json) file. We suggest to install this file to the default path of `/tmp/kameleoon/client-php.json`. La siguiente tabla muestra las propiedades disponibles que puede configurar:

| Clave                                                                                     | Descripción                                                                                                                                                                                                                                                                                                                                                                 | Valor predeterminado         |
| ----------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- |
| `clientId` / `client_id` (*obligatorio*)                                                  | Necesario para la autenticación con el servicio de Kameleoon. Para encontrar su `client_id`, consulte la documentación de [credenciales de API](/user-manual/account-and-team-management/users-and-teams/api-credentials).                                                                                                                                                  |                              |
| `clientSecret` / `client_secret` (*obligatorio*)                                          | Necesario para la autenticación con el servicio de Kameleoon. Para encontrar su `client_secret`, consulte la documentación de [credenciales de API](/user-manual/account-and-team-management/users-and-teams/api-credentials).                                                                                                                                              |                              |
| `kameleoonWorkDir` / `kameleoon_work_dir` (*opcional*)                                    | Specifies a working directory for the PHP client (which will create files in this directory). The directory needs to be writable by the PHP user.                                                                                                                                                                                                                           | `/tmp/kameleoon/client-php/` |
| `refreshIntervalMinute` / `refresh_interval_minute` (*opcional*)                          | Specifies the refresh interval, in minutes, that the SDK fetches the configuration for the active experiments and feature flags. The value determines the maximum time it takes to propagate changes, such as activating or deactivating feature flags or launching experiments, to your production servers.                                                                | `60` minutos                 |
| `defaultTimeoutMillisecond` / `default_timeout_millisecond` (*opcional*)                  | Specifies the timeout, in milliseconds, for network requests from the SDK. Set the value to `30` seconds or more if you do not have a stable connection. Some methods have an additional parameter that you can use to override the default timeout for that particular method. If you do not specify the timeout for a method explicitly, the SDK uses this default value. | `10000` milisegundos         |
| `cookieOptions->topLevelDomain` / `cookie_options.domain` *(obligatorio en modo híbrido)* | El dominio de nivel superior actual de su sitio web. Use el formato: `example.com`. No incluya `https://`, `www` ni otros subdominios. Kameleoon utiliza esta información para establecer la cookie correspondiente en el dominio de nivel superior.                                                                                                                        | `null`                       |
| `cookieOptions->secure` / `cookie_options.secure` (*opcional*)                            | Controls the **Secure** cookie attribute.                                                                                                                                                                                                                                                                                                                                   | `false`                      |
| `cookieOptions->httpOnly` / `cookie_options.http_only` (*opcional*)                       | Controls the **HttpOnly** cookie attribute.                                                                                                                                                                                                                                                                                                                                 | `false`                      |
| `cookieOptions->sameSite` / `cookie_options.samesite` (*opcional*)                        | Controls the **SameSite** cookie attribute.                                                                                                                                                                                                                                                                                                                                 | `Lax`                        |
| `environment` / `environment` (*opcional*)                                                | Entorno desde el cual se debe utilizar la configuración del feature flag. El valor puede ser `production`, `staging` o `development`. Consulte el artículo de [gestión de entornos](/user-manual/experimentation/feature-experimentation/configure-your-feature-flags/manage-environments) para más detalles.                                                               | `production`                 |
| `networkDomain` / `network_domain` (*opcional*)                                           | Dominio personalizado utilizado por los SDKs para las solicitudes salientes, a menudo para proxy. Debe ser un dominio válido (por ejemplo, example.com o sub.example.com). Los formatos no válidos se sustituyen por el valor de Kameleoon.                                                                                                                                 | `null`                       |
| `requestBodySizeLimitBytes` / `request_body_size_limit_bytes` *(optional)*                | Limits the size of tracking packages (in bytes) — files that store data collected between cron job runs. In some cases, reducing the package size may be necessary due to server or network restrictions. The maximum allowed value is 2.5 MB (`2621440` bytes).                                                                                                            | `2621440`                    |
| `debugMode` / `debug_mode` *(deprecated)*                                                 | The parameter sends additional information to our tracking servers to help analyze issues. It should usually be off (**false**), but activating it (**true**) has no impact on SDK performance. This field is deprecated and will be removed in SDK version `5.0.0`. Use [`KameleoonLogger::setLogLevel`](#niveles-de-registro) instead.                                    | `false`                      |

<Note>
  If you do not use the default path (`/tmp/kameleoon/client-php.json`) for the configuration file, you will need to:

  * pass your configuration file's path as a third argument to the `KameleoonClientFactory::create()` method;
  * modify your crontab entry to add the --conf argument to the job script (so, for instance, it would be `bash /usr/local/opt/bin/kameleoon-client-php-process-queries.sh --conf /my/path/kameleoon.json`).
</Note>

<Note>
  To learn more about `client_id` and `client_secret`, and how to obtain them, refer to the [API credentials](/user-manual/account-and-team-management/users-and-teams/api-credentials) article. Tenga en cuenta que el Kameleoon PHP SDK uses the Automation API and follows the OAuth 2.0 client credentials flow.
</Note>

#### Inicialización del cliente Kameleoon

After installing the SDK into your application and configuring the correct credentials (in `/tmp/kameleoon/client-php.json`), the next step is to create the Kameleoon client in your application code. Por ejemplo:

```php theme={null}
require "vendor/autoload.php";

use Kameleoon\KameleoonClientConfig;
use Kameleoon\KameleoonClientFactory;
use Kameleoon\Exception\ConfigCredentialsInvalid;
use Kameleoon\Exception\KameleoonException;
use Kameleoon\Exception\SiteCodeIsEmpty;

$siteCode = "a8st4f59bj";

try {
    // Read from default configuration path: "/tmp/kameleoon/php-client/"
    $kameleoonClient = KameleoonClientFactory::create($siteCode);
} catch (SiteCodeIsEmpty $ex) {
    // indicates that provided site code is empty
} catch (ConfigCredentialsInvalid $ex) {
    // indicates that provided clientId / clientSecret are not valid
} catch (KameleoonException $ex) {
    // probably indicates that the SDK is unable to access the **Kameleoon working directory**
}

try {
    $kameleoonClient = KameleoonClientFactory::create($siteCode, "custom/file/path/client-php.json");
} catch (SiteCodeIsEmpty $ex) {
    // indicates that provided site code is empty
} catch (ConfigCredentialsInvalid $ex) {
    // indicates that provided clientId / clientSecret are not valid
} catch (KameleoonException $ex) {
    // probably indicates that the SDK is unable to access the **Kameleoon working directory**
}

try {
    $cookieOptions = KameleoonClientConfig::createCookieOptions(
        "example.com", // domain: optional, but strictly recommended
        false, // secure: optional (false by default)
        false, // httponly: optional (false by default)
        "Lax" // samesite: optional (Lax by default)
    );
    $config = new KameleoonClientConfig(
        "<clientId>", // clientId: mandatory
        "<clientSecret>", // clientSecret: mandatory
        "/tmp/kameleoon/php-client/", // kameleoonWorkDir: optional / ("/tmp/kameleoon/php-client/" by default)
        60, // refreshIntervalMinute: in minutes, optional (60 minutes by default)
        10_000, // defaultTimeoutMillisecond: in milliseconds, optional (10_000 ms by default)
        false, // debugMode: optional (false by default)
        $cookieOptions, // cookieOptions: optional
        "development", // environment: optional ("production" by default)
        "example.com", // networkDomain: optional (null by default)
        1024*1024, // requestBodySizeLimitBytes: optional (2560 * 1024 by default)
    );
    $kameleoonClient = KameleoonClientFactory::createWithConfig($siteCode, $config);
} catch (SiteCodeIsEmpty $ex) {
    // indicates that provided site code is empty
} catch (ConfigCredentialsInvalid $ex) {
    // indicates that provided clientId / clientSecret are not valid
} catch (KameleoonException $ex) {
    // probably indicates that the SDK is unable to access the **Kameleoon working directory**
}
```

A KameleoonClient is a singleton object that acts as a bridge between your application and the Kameleoon platform. It includes all the methods and properties you need to run an experiment. Tenga en cuenta que el SDK takes its settings from a [configuration file.](#configuración-adicional) De forma predeterminada, the path `/tmp/kameleoon/client-php.json` will be used, but you can use a different path for the configuration file by providing an optional third argument to the `KameleoonClientFactory::create()` method.

<Note>
  It's your responsibility as the application developer to use correct logic in your application code within the context of A/B testing via Kameleoon. A good practice is to always assume that the current visitor can be left out of the experiment because the experiment has not yet been launched. Leaving out the current visitor is simple, as it corresponds to the implementation of the default / reference variation logic. The code samples in the next paragraph show examples of such an approach.
</Note>

#### Activación de un feature flag

##### Asignación de un ID único a un usuario

Para asignar un ID único a un usuario, puede utilizar el método [`getVisitorCode()`](#getvisitorcode). Si no existe un **visitor code** (en la cookie de los encabezados de la solicitud), el método genera un ID único aleatorio o utiliza un `defaultVisitorCode` que usted haya generado. A continuación, el ID se establece en una cookie en los encabezados de respuesta.

Si está usando Kameleoon en [modo híbrido](/developer-docs/feature-experimentation/get-started/hybrid-experimentation), llamar al método `getVisitorCode()` garantiza que el ID único (**visitor code**) se comparta entre el archivo de aplicación `engine.js` (anteriormente llamado `kameleoon.js`) y el SDK.

##### Recuperación de la configuración de un flag

Para implementar un feature flag en su código, primero debe crear el feature flag en su cuenta de Kameleoon.

Para determinar el estado o la variación de un feature flag para un usuario específico, debe utilizar el método [`getVariation()`](#getvariation) o [`isFeatureActive()`](#isfeatureactive) para recuperar la configuración basada en el `featureKey`.

El método `getVariation()` gestiona tanto los feature flags simples con estados ON/OFF como los flags más complejos con múltiples variaciones. El método recupera la variación adecuada para el usuario comprobando las reglas de la funcionalidad, asignando la variación y devolviéndola en función del `featureKey` y el `visitorCode`.

El método `isFeatureActive()` puede utilizarse si desea recuperar la configuración de un feature flag simple que solo tiene un estado ON u OFF, a diferencia de los feature flags más complejos con múltiples variaciones u opciones de segmentación.

If your feature flag has associated variables (such as specific behaviors tied to each variation) `getVariation()` also enables you to access the [`Variation`](#variation) object, which provides details about the assigned variation and its associated experiment. This method checks whether the user is targeted, finds the visitor’s assigned variation, and saves it to storage. When `track=true`, the SDK will send the exposure event to the specified experiment on one of the next tracking request, which is automatically performed by the cron job. De forma predeterminada, its interval is 1 minute.

El método `getVariation()` le permite controlar si se realiza el seguimiento. Si `track=false`, el SDK no enviará eventos de exposición. Esto es útil si prefiere no realizar el seguimiento de los datos a través del SDK y, en su lugar, basarse en el seguimiento del lado del cliente gestionado por el motor de Kameleoon, por ejemplo. Además, establecer `track=false` resulta útil cuando se utiliza el método `getVariations()`, donde puede que solo necesite las variaciones de todos los flags sin desencadenar eventos de seguimiento. Si desea saber más sobre cómo funciona el seguimiento, consulte [este artículo](/developer-docs/feature-experimentation/technical-reference/faq-global#when-does-the-sdk-send-a-tracking-request-for-analytics)

##### Adición de puntos de datos para segmentar a un usuario o filtrar / desglosar visitas en informes

Para segmentar a un usuario, asegúrese de haber añadido los puntos de datos relevantes a su perfil antes de recuperar la variación de la funcionalidad o comprobar si el flag está activo. Utilice el método [`addData()`](#adddata) para añadir estos puntos de datos al perfil del usuario.

Para recuperar puntos de datos recopilados en otros dispositivos o acceder a datos pasados del usuario (recopilados en el lado del cliente cuando se utiliza Kameleoon en modo híbrido), utilice el método [`getRemoteVisitorData()`](#getremotevisitordata). Este método obtiene datos de los servidores de forma asíncrona. Es importante llamar a `getRemoteVisitorData()` *antes* de recuperar la variación o comprobar si el feature flag está activo, ya que estos datos pueden ser necesarios para asignar a un usuario a una variación determinada.

Para obtener más información sobre las condiciones de segmentación disponibles, consulte el [artículo detallado sobre este tema](/developer-docs/feature-experimentation/targeting-and-segmentation/native-segmentation).

Además, los puntos de datos que añade al perfil del visitante estarán disponibles al analizar sus experimentos, lo que le permite filtrar y desglosar sus resultados por factores como el dispositivo y el navegador. El modo híbrido de Kameleoon recopila automáticamente una variedad de puntos de datos en el lado del cliente, lo que facilita desglosar sus resultados en función de estos puntos de datos previamente recopilados. Consulte la lista completa [aquí](/es/user-manual/experiment-analytics/analyze-results/results-page/results-page-settings#desglose-de-audiencia).

Si necesita realizar el seguimiento de puntos de datos adicionales más allá de los que se recopilan automáticamente, puede utilizar la [funcionalidad de Custom Data](#customdata) de Kameleoon. Custom Data le permite capturar y analizar información específica relevante para sus experimentos. No olvide llamar al método [`flush()`](#flush) para enviar los datos recopilados a los servidores de Kameleoon para su análisis.

<Note>
  Para asegurarse de que sus resultados sean precisos, se recomienda filtrar los bots utilizando el tipo de dato [`UserAgent`](#useragent).
</Note>

##### Seguimiento de conversiones de objetivos

Cuando un usuario completa una acción deseada (como realizar una compra), se registra como una conversión. Para hacer seguimiento de las conversiones, utilice el método [`trackConversion()`](#trackconversion) y proporcione los parámetros requeridos `visitorCode` y `goalId`.

La solicitud de seguimiento de conversiones se enviará junto con la siguiente solicitud de seguimiento programada, que el SDK envía a intervalos regulares (definidos en el crontab de intervalo de seguimiento). Si prefiere enviar la solicitud de inmediato, utilice el método [`flush()`](#flush) con el parámetro `instant=true`.

##### Envío de eventos a soluciones de analítica

Para realizar el seguimiento de las conversiones y enviar eventos de exposición a su solución de analítica de cliente, primero debe implementar Kameleoon en [modo híbrido](/developer-docs/feature-experimentation/get-started/hybrid-experimentation/). A continuación, utilice el método [`getEngineTrackingCode()`](#getenginetrackingcode).

El método `getEngineTrackingCode()` recupera el código de seguimiento único necesario para enviar eventos de exposición a su solución de analítica. El uso de este método le permite registrar eventos y enviarlos a la plataforma de analítica que desee.

### Experimentación entre dispositivos

Para dar soporte a los visitantes que acceden a una aplicación desde varios dispositivos, Kameleoon permite sincronizar los datos del visitante previamente recopilados entre cada uno de sus dispositivos y reconciliar su historial de visitas entre dispositivos mediante la experimentación entre dispositivos. Los casos de estudio y la información detallada sobre cómo Kameleoon gestiona los datos entre dispositivos están disponibles en el [artículo sobre experimentación entre dispositivos](/developer-docs/cross-device-experimentation).

#### Sincronización de datos personalizados entre dispositivos

Aunque la sincronización de mapeo personalizado se utiliza para alinear los datos del visitante entre dispositivos, no siempre es necesaria. A continuación se presentan dos escenarios en los que no se requiere la sincronización de mapeo personalizado:

**Mismo ID de usuario en todos los dispositivos**
Si el mismo ID de usuario se utiliza de forma consistente en todos los dispositivos, la sincronización se gestiona automáticamente sin necesidad de una sincronización de mapeo personalizado. Basta con llamar al método `getRemoteVisitorData()` cuando desee sincronizar los datos recopilados entre varios dispositivos.

**Instancias multi-servidor con IDs consistentes**
En configuraciones complejas que involucran varios servidores (por ejemplo, instancias de servidor distribuidas), donde el mismo ID de usuario está disponible en todos los servidores, la sincronización entre servidores (con `getRemoteVisitorData()`) es suficiente sin necesidad de una sincronización adicional de mapeo personalizado.

Los clientes que necesiten datos adicionales pueden consultar la descripción del método [`getRemoteVisitorData()`](#getremotevisitordata) para obtener más orientación. En el código siguiente se asume que el mismo identificador único (en este caso, el `visitorCode`, que también puede denominarse `userId`) se utiliza de manera consistente entre los dos dispositivos para una recuperación precisa de los datos.

<Note>
  Si desea sincronizar los datos recopilados en tiempo real, debe elegir el ámbito **Visitor** para sus datos personalizados.
</Note>

```php title="Device A" theme={null}
// In this example, Custom data with index `90` was set to "Visitor" scope on Kameleoon.
const VISITOR_SCOPE_CUSTOM_DATA_INDEX = 90;

$kameleoonClient->addData($visitorCode, new CustomData(VISITOR_SCOPE_CUSTOM_DATA_INDEX, "your data"));
$kameleoonClient->flush($visitorCode);
```

```php title="Device B" theme={null}
// Call the `getRemoteVisitorData` method before working with the data.
$kameleoonClient->getRemoteVisitorData($visitorCode);

// After the call, the SDK on Device B will have access to CustomData of Visitor scope defined on Device A.
// So, "your data" will be available to target and track the visitor.
```

#### Uso de datos personalizados para la fusión de sesiones

La [experimentación entre dispositivos](/developer-docs/cross-device-experimentation) permite combinar el historial de un visitante en cada uno de sus dispositivos (reconciliación de historial). La reconciliación de historial permite fusionar diferentes sesiones de un visitante en una sola. Para reconciliar el historial de visitas, utilice [`CustomData`](#customdata) para proporcionar un identificador único del visitante. Para más información, consulte la [documentación dedicada](/developer-docs/cross-device-experimentation/#activating-cross-device-history-reconciliation).

Una vez habilitada la reconciliación entre dispositivos, al llamar a [`getRemoteVisitorData()`](#getremotevisitordata) con el parámetro `userId` se recuperan todos los datos conocidos para un usuario determinado.

Las sesiones con el mismo identificador siempre verán la misma variación en un experimento. En la vista Visitor de las páginas de resultados de su experimento, estas sesiones aparecerán como un único visitante.

La configuración del SDK garantiza que las sesiones asociadas siempre vean la misma variación del experimento. Sin embargo, existen algunas limitaciones en cuanto a la asignación de variaciones entre dispositivos. Estas limitaciones se describen [aquí](/developer-docs/cross-device-experimentation#critical-points-and-practical-insights).

Siga la guía de [activación de la reconciliación de historial entre dispositivos](#experimentación-entre-dispositivos) para configurar sus datos personalizados en la plataforma Kameleoon.

Posteriormente, puede usar el SDK de forma normal. Los siguientes métodos pueden ser útiles en el contexto de la fusión de sesiones:

* `getRemoteVisitorData()` con `UniqueIdentifier(true)` añadido: para recuperar datos de todos los visitantes vinculados.
* [`trackConversion()`](#trackconversion) o [`flush()`](#flush) con datos `UniqueIdentifier(true)` añadidos: para hacer seguimiento de datos de un visitante específico asociado con otro visitante.

<Tip>
  Como el dato personalizado que utiliza como identificador debe configurarse con ámbito **Visitor**, necesita usar la [sincronización de datos personalizados entre dispositivos](/developer-docs/cross-device-experimentation) para recuperar el identificador con el método [`getRemoteVisitorData()`](#getremotevisitordata) en cada dispositivo.
</Tip>

A continuación se muestra un ejemplo de cómo usar datos personalizados para la fusión de sesiones.

```php theme={null}
// In this example, `91` represents the Custom Data's index
// configured as a unique identifier in Kameleoon.
const MAPPING_INDEX = 91;
const FEATURE_KEY = "ff123";

// 1. Before the visitor is authenticated

// Retrieve the variation for an unauthenticated visitor.
// Assume `anonymousVisitorCode` is the randomly generated ID for that visitor.
$anonymousVariation = $kameleoonClient->getVariation($anonymousVisitorCode, FEATURE_KEY);

// 2. After the visitor is authenticated

// Assume `userId` is the authenticates visitor's visitor code.
$kameleoonClient->addData($anonymousVisitorCode, new CustomData(MAPPING_INDEX, $userId));
$kameleoonClient->flush($anonymousVisitorCode, null, null, true);

// Indicate that `userId` is a unique identifier.
$kameleoonClient->addData($userId, new UniqueIdentifier(true));

// 3. After the visitor has been authenticated

// Retrieve the variation for the `userId`, which will match the anonymous visitor code's variation.
$userVariation = $kameleoonClient->getVariation($userId, FEATURE_KEY);
$isSameVariation = $userVariation->key == $anonymousVariation->key; // true

// The `userId` and `anonymousVisitorCode` are now linked and tracked as a single visitor.
$kameleoonClient->trackConversion($userId, 123, 10.0);

// Additionally, the linked visitors will share all fetched remote visitor data.
$kameleoonClient->getRemoteVisitorData($userId);
```

En este ejemplo, la aplicación tiene una página de inicio de sesión. Como el ID de usuario es desconocido en el momento del inicio de sesión, se utiliza un identificador de visitante anónimo generado por el método [`getVisitorCode()`](#getvisitorcode). Después de que el usuario inicia sesión, el visitante anónimo se asocia con el ID de usuario y se utiliza como identificador único del visitante.

### Uso de una clave de bucketing personalizada

De forma predeterminada, Kameleoon utiliza un ID de visitante anónimo y único (`visitorCode`) para asignar usuarios a las variaciones de los feature flags. Este ID se genera y almacena habitualmente en el dispositivo del usuario (en una cookie del navegador para los SDKs del lado del cliente y del lado del servidor, y en almacenamiento persistente para los SDKs móviles). Sin embargo, en determinados escenarios puede necesitar asegurarse de que todos los usuarios de la misma organización vean la misma variante de un feature flag.

La opción **Custom Bucketing Key** le permite anular este comportamiento predeterminado proporcionando su propio identificador personalizado para el bucketing. Esta anulación garantiza que la lógica de asignación de Kameleoon utilice la clave que usted especifique en lugar del `visitorCode` predeterminado.

#### Casos de uso

El uso de una clave de bucketing personalizada es esencial para mantener la consistencia y precisión en las asignaciones de sus feature flags, especialmente en estas situaciones:

* **Experimentos a nivel de cuenta u organización:** Para productos B2B o escenarios en los que desea asignar a todos los usuarios de la misma organización a la misma variación, puede utilizar un identificador como `accountId`. Las claves de bucketing personalizadas son cruciales para probar mediante A/B funcionalidades que afecten a todo un equipo o empresa.

Al implementar una clave de bucketing personalizada, garantiza una mayor consistencia y precisión en sus experimentos, lo que se traduce en resultados más fiables y en una mejor experiencia de usuario.

#### Detalles técnicos

Cuando configura una clave de bucketing personalizada para un feature flag, proporciona a Kameleoon un identificador específico de los datos de su aplicación:

```php theme={null}
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\CustomData(1, "newVisitorCode"));
```

* **Proporcionar la clave personalizada:** Usted proporciona su identificador personalizado al SDK de Kameleoon mediante el método [`addData()`](#adddata). En este método, pasará la clave de bucketing personalizada que haya elegido como un objeto [`CustomData`](#customdata). Aquí, `newVisitorCode` hace referencia al identificador que desea usar para el bucketing (por ejemplo, el nuevo `userId` o `accountId`).

<Warning>
  Para que la clave de bucketing personalizada funcione correctamente, también debe definirse y configurarse para el feature flag durante el proceso de creación o edición del flag. Sin esta configuración correspondiente, el bucketing del SDK no aplicará su clave personalizada. Para obtener instrucciones detalladas sobre cómo configurar esto en Kameleoon, consulte este [artículo](/user-manual/experimentation/feature-experimentation/create-and-manage-flags/create-a-feature-flag#Advanced_Flag_Settings).
</Warning>

* **Lógica de bucketing:** Una vez que se proporciona una clave de bucketing personalizada a través del método `addData()`, todos los cálculos de hash para asignar usuarios a las variaciones utilizarán este `newVisitorCode` (su clave personalizada) en lugar del `visitorCode` predeterminado. Usar el `newVisitorCode` significa que la decisión de bucketing queda ligada a su identificador personalizado, garantizando asignaciones consistentes en los diversos contextos en los que esté presente ese identificador.
* **Seguimiento de datos y analítica:** Es crucial tener en cuenta que, aunque el `newVisitorCode` (su clave personalizada) se utiliza para las decisiones de bucketing, **todos los datos posteriores (eventos de seguimiento y conversiones, por ejemplo) se envían y se asocian con el `visitorCode` *original*.** Esta separación garantiza que su analítica refleje con precisión los recorridos e interacciones individuales de los usuarios dentro del contexto más amplio de su experimento, incluso cuando el bucketing se realiza a un nivel superior (como una cuenta) o a través de varios dispositivos/sesiones. Sus datos originales del visitante permanecen intactos para una elaboración de informes completa.

#### Requisitos técnicos

Para utilizar eficazmente una clave de bucketing personalizada:

* The key must be a `string`.
* Debe ser única para la entidad que pretende agrupar (por ejemplo, si utiliza un `userId`, el ID de cada usuario debe ser único).
* La clave debe estar disponible para el SDK en el momento exacto en que se evalúa la decisión del feature flag para ese usuario o solicitud.

### Condiciones de segmentación

Los SDKs de Kameleoon admiten una variedad de condiciones de segmentación predefinidas que puede usar para segmentar a los usuarios en sus campañas. Para ver la lista de condiciones que admite este SDK, consulte [usar el historial de visitas para segmentar a los usuarios](/developer-docs/feature-experimentation/targeting-and-segmentation/native-segmentation).

También puede utilizar sus propios [datos externos para segmentar a los usuarios](/developer-docs/apis/data-api-rest/tutorials/storing-and-retrieving-external-data-to-target-users).

### Registro de eventos

El SDK genera registros que reflejan diversos procesos internos y problemas.

#### Niveles de registro

El SDK admite la configuración para limitar el registro mediante un nivel de log.

```php theme={null}
use Kameleoon\logging\KameleoonLogger;
use Kameleoon\logging\LogLevel;

// The `NONE` log level does not allow logging.
KameleoonLogger::setLogger(LogLevel::NONE);

// The `ERROR` log level only allows logging issues that may affect the SDK's primary behavior.
KameleoonLogger::setLogger(LogLevel::ERROR);

// The `WARNING` log level allows logging issues which may require additional attention.
// It extends the `ERROR` log level.
// The `WARNING` log level is a default log level.
KameleoonLogger::setLogger(LogLevel::WARNING);

// The `INFO` log level allows logging general information on the SDK's internal processes.
// It extends the `WARNING` log level.
KameleoonLogger::setLogger(LogLevel::INFO);

// The `DEBUG` level logs additional details about the SDK’s internal processes and extends the `INFO` level
// with more granular. diagnostic output.
// This information is not intended for end-user interpretation but can be sent to our support team
// to assist with internal troubleshooting.
KameleoonLogger::setLogger(LogLevel::DEBUG);
```

#### Gestión personalizada de los registros

El SDK escribe sus registros en la salida de la consola de forma predeterminada. Este comportamiento puede anularse.

<Note>
  El filtrado por nivel de log se realiza de forma independiente de la lógica de gestión de los registros.
</Note>

```php theme={null}
use Kameleoon\logging\KameleoonLogger;
use Kameleoon\logging\Logger;
use Kameleoon\logging\LogLevel;
use Monolog\Logger as MonologLogger;

public class CustomLogger implements Logger {
    // Monolog logger
    private MonologLogger $inner;

    public function __construct(MonologLogger $inner)
    {
        $this->inner = $inner;
    }

    // `log` method accepts logs from the SDK
    public function log($level, string $message): void
    {
        // Custom log handling logic here. For example:
        switch ($level) {
            case LogLevel::ERROR:
                $this->inner->error($message);
                break;
            case LogLevel::WARNING:
                $this->inner->warning($message);
                break;
            case LogLevel::INFO:
                $this->inner->info($message);
                break;
            case LogLevel::DEBUG:
                $this->inner->debug($message);
                break;
        }
    }
}


// Log level filtering is applied separately from log handling logic.
// The custom logger will only accept logs that meet or exceed the specified log level.
// Ensure the log level is set correctly.
KameleoonLogger::setLogLevel(LogLevel::DEBUG); // Optional; defaults to `LogLevel::WARNING`.
KameleoonLogger::setLogger(new CustomLogger($inner));
```

## Referencia

This is a full reference documentation of the PHP SDK.

### Inicialización

#### create()

This method in `Kameleoon\KameleoonClientFactory` creates a `KameleoonClient` instance by providing your SDK configuration in a configuration file. You need to initialize the SDK by creating this instance of `KameleoonClient` before you can use other SDK methods. All interactions with the SDK use this `KameleoonClient` instance. To provide the configuration as a `KameleoonClientConfig` object instead, see the [`createWithConfig`](#createWithConfig) method.

```php theme={null}
require "vendor/autoload.php";

use Kameleoon\KameleoonClientFactory;
use Kameleoon\Exception\ConfigCredentialsInvalid;
use Kameleoon\Exception\KameleoonException;
use Kameleoon\Exception\SiteCodeIsEmpty;

$siteCode = "a8st4f59bj";

try {
    // Read from default configuration path: "/tmp/kameleoon/php-client/"
    $kameleoonClient = KameleoonClientFactory::create($siteCode);
} catch (SiteCodeIsEmpty $ex) {
    // indicates that provided site code is empty
} catch (ConfigCredentialsInvalid $ex) {
    // indicates that provided clientId / clientSecret are not valid
} catch (KameleoonException $ex) {
    // probably indicates that the SDK is unable to access the **Kameleoon working directory**
}

try {
    $kameleoonClient = KameleoonClientFactory::create($siteCode, "custom/file/path/client-php.json");
} catch (SiteCodeIsEmpty $ex) {
    // indicates that provided site code is empty
} catch (ConfigCredentialsInvalid $ex) {
    // indicates that provided clientId / clientSecret are not valid
} catch (KameleoonException $ex) {
    // probably indicates that the SDK is unable to access the **Kameleoon working directory**
}
```

##### Argumentos

| Nombre                | Tipo   | Descripción                                                                                                                                          |
| --------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| siteCode              | String | Es la [clave única](/user-manual/faq#how-do-i-find-my-sitecode) del proyecto de Kameleoon que está utilizando con el SDK. Este campo es obligatorio. |
| configurationFilePath | String | Ruta al archivo de configuración del SDK. This field is optional and set to `/tmp/kameleoon/client-php.json` by default.                             |

##### Valor de retorno

| Type                      | Description                                                                                                  |
| ------------------------- | ------------------------------------------------------------------------------------------------------------ |
| Kameleoon\KameleoonClient | An instance of the **KameleoonClient** class that will be used to manage your experiments and feature flags. |

##### Excepciones lanzadas

| Tipo                     | Descripción                                                                                                                                        |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| SiteCodeIsEmpty          | Exception indicating that the requested credentials were not provided (either using the configuration file or the config parameter in the method). |
| ConfigCredentialsInvalid | Exception indicating that the requested credentials were not provided (either using the configuration file or the config parameter in the method). |
| KameleoonException       | Exception that may indicate that the SDK is unable to access the **Kameleoon working directory**.                                                  |

#### createWithConfig()

This method in `Kameleoon\KameleoonClientFactory` creates a `KameleoonClient` instance and allows you to pass your SDK configuration in a `KameleoonClientConfig` object. You need to initialize the SDK by creating this `KameleoonClient` instance before you can use other SDK methods. All interactions with the SDK use this `KameleoonClient` instance. To provide your SDK configuration in a file instead, use the [`create`](#create) method.

```php theme={null}
require "vendor/autoload.php";

use Kameleoon\KameleoonClientConfig;
use Kameleoon\KameleoonClientFactory;
use Kameleoon\Exception\ConfigCredentialsInvalid;
use Kameleoon\Exception\KameleoonException;
use Kameleoon\Exception\SiteCodeIsEmpty;

$siteCode = "a8st4f59bj";

try {
    $cookieOptions = KameleoonClientConfig::createCookieOptions(
        "example.com", // domain: optional, but strictly recommended
        false, // secure: optional (false by default)
        false, // httponly: optional (false by default)
        "Lax" // samesite: optional (Lax by default)
    );
    $config = new KameleoonClientConfig(
        "<clientId>", // clientId: mandatory
        "<clientSecret>", // clientSecret: mandatory
        "/tmp/kameleoon/php-client/", // kameleoonWorkDir: optional / ("/tmp/kameleoon/php-client/" by default)
        60, // refreshIntervalMinute: in minutes, optional (60 minutes by default)
        10_000, // defaultTimeoutMillisecond: in milliseconds, optional (10_000 ms by default)
        false, // debugMode: optional (false by default)
        $cookieOptions, // cookieOptions: optional
        "development", // environment: optional ("production" by default)
        "example.com", // networkDomain: optional (null by default)
        1024*1024, // requestBodySizeLimitBytes: optional (2560 * 1024 by default)
    );
    $kameleoonClient = KameleoonClientFactory::create($siteCode, $config);
} catch (SiteCodeIsEmpty $ex) {
    // indicates that provided site code is empty
} catch (ConfigCredentialsInvalid $ex) {
    // indicates that provided clientId / clientSecret are not valid
} catch (KameleoonException $ex) {
    // probably indicates that the SDK is unable to access the **Kameleoon working directory**
}
```

##### Argumentos

| Nombre          | Tipo                  | Descripción                                                                                                                           |
| --------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| siteCode        | String                | Code of the website you want to run experiments on. This unique code ID can be found in the Kameleoon app. Este campo es obligatorio. |
| kameleoonConfig | KameleoonClientConfig | Configuration SDK object that you pass. Este campo es opcional.                                                                       |

##### Valor de retorno

| Tipo            | Descripción                                                                                             |
| --------------- | ------------------------------------------------------------------------------------------------------- |
| KameleoonClient | An instance of the **KameleoonClient** class that you use to manage your experiments and feature flags. |

##### Excepciones lanzadas

| Tipo                     | Descripción                                                                                                                                        |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| SiteCodeIsEmpty          | Exception indicating that the requested credentials were not provided (either using the configuration file or the config parameter in the method). |
| ConfigCredentialsInvalid | Exception indicating that the requested credentials were not provided (either using the configuration file or the config parameter in the method). |
| KameleoonException       | Exception that may indicate that the SDK is unable to access the **Kameleoon working directory**.                                                  |

### Feature flags y variaciones

#### isFeatureActive()

* 📨 *Envía datos de seguimiento a Kameleoon (dependiendo del parámetro `track`)*

<Note>
  This method was previously called `activateFeature`, which was removed in SDK version `4.0.0`.
</Note>

Este método toma un **visitorCode** and **featureKey** as mandatory arguments to check if the specified feature will be active for a given user.

If such a user has never been associated with this feature flag, the SDK returns a boolean value randomly (**true** if the user should have this feature or **false** if not). If a user with a given **visitorCode** is already registered with this feature flag, it will detect the previous **FeatureFlag** value.

You have to make sure that proper error handling is set up in your code como se muestra en el ejemplo to the right to catch potential exceptions.

If you specify a `visitorCode`, the `isFeatureActive()` method uses it as the unique visitor identifier, which is useful for [cross-device experimentation](/developer-docs/apis/data-api-rest/tutorials/storing-and-retrieving-external-data-to-target-users). Cuando especifica un `visitorCode` y establece el parámetro `isUniqueIdentifier` en `true`, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.

<Note>
  El parámetro `isUniqueIdentifier` está obsoleto. Utilice en su lugar [`UniqueIdentifier`](#uniqueidentifier).

  `isUniqueIdentifier` también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al `visitorCode` anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
</Note>

<Note>
  Kameleoon uses tracking to count sessions and visitors when you call certain methods, such as `isFeatureActive()`, `getVariation()` or `getVariations()`.

  Use el valor predeterminado `true` para el parámetro `track` cuando exponga a los visitantes a una variación y necesite contarlos. Establezca el parámetro `track` en `false` solo si llama a estos métodos antes de exponer a los visitantes.

  Por ejemplo, if you call `getVariations()` to retrieve all variations before you expose visitors, set the `track` parameter to `false`. This setting prevents Kameleoon from prematurely counting a session. You can then trigger tracking later when you explicitly expose the visitor.

  Kameleoon sends tracking data every second by default. You can configure this interval up to five seconds using the tracking interval configuration option. Kameleoon groups tracking events into a single session as long as the interval between events is less than 30 minutes. If more than 30 minutes elapse between tracking events, Kameleoon counts the events as separate sessions. A visit appears in your reports 30 minutes after the last recorded event in the session.
</Note>

```php theme={null}
$visitorCode = $kameleoonClient->getVisitorCode();
$featureKey = "new_checkout";
$hasNewCheckout = false;

try {
    $hasNewCheckout = $kameleoonClient->isFeatureActive($visitorCode, $featureKey, $timeout);
    // disabling tracking
    $hasNewCheckout = $kameleoonClient->isFeatureActive($visitorCode, $featureKey, $timeout, null, false);
} catch (Kameleoon\Exception\FeatureNotFound $e) {
    // Feature toggle not yet activated on Kameleoon's side - we consider the feature inactive.
    $hasNewCheckout = false;
} catch (Kameleoon\Exception\VisitorCodeInvalid $e) {
    // VisitorCode, which you passed to a method, is invalid and can't be accepted.
} catch (Kameleoon\Exception\DataFileInvalid $e) {
    // It appears that the configuration has not been loaded and
    // there is no previously saved version of the configuration available.
} catch (Exception $e) {
    // This is a generic Exception handler which will handle all exceptions.
    echo "Exception: ",  $e->getMessage(), "\n";
}
if ($hasNewCheckout) {
    // Implement new checkout code here.
}
```

<Warning>
  The `isFeatureActive()` method evaluates the served variant, not the master flag state. If you exclude rules, the method uses the **Then, for everyone else serve** default state. If you select **Off** for this default state, the method always returns `false` even when the master feature flag is **On**.
</Warning>

##### Argumentos

| Nombre                        | Tipo   | Descripción                                                                                                                                                                                                                                                                           |
| ----------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorCode                   | string | Identificador único del usuario. Este campo es obligatorio.                                                                                                                                                                                                                           |
| featureKey                    | string | Clave de la funcionalidad que desea exponer a un usuario. Este campo es obligatorio.                                                                                                                                                                                                  |
| timeout                       | ?int   | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the [`default_timeout`](#configuración-adicional) specified in your configuration. |
| isUniqueIdentifier (Obsoleto) | ?bool  | Parámetro opcional para indicar si el visitorCode es un identificador único. If not provided, el valor predeterminado es `null`. The field is optional.                                                                                                                               |
| track                         | bool   | An optional parameter to enable or disable tracking of the feature evaluation (`true` by default).                                                                                                                                                                                    |

##### Valor de retorno

| Tipo | Descripción                                                               |
| ---- | ------------------------------------------------------------------------- |
| bool | Value of the feature flag that is registered for a given **visitorCode**. |

##### Excepciones lanzadas

| Tipo               | Descripción                                                                                                                                                                                                                                                                                                  |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| FeatureNotFound    | Exception indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side). |
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters).                                                                                                                                                                                                     |
| DataFileInvalid    | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available.                                                                                                                                                                     |

#### getVariation()

* 📨 *Envía datos de seguimiento a Kameleoon (dependiendo del parámetro `track`)*

Recupera la [`Variation`](#variation) asignada a un visitante dado para un feature flag específico.

Este método toma un `visitorCode` and `featureKey` as mandatory arguments. The `track` argument is optional and defaults to `true`.

Devuelve la `Variation` asignada al visitante. Si el visitante no está asociado con ninguna regla de feature flag, el método devuelve la `Variation` predeterminada para el feature flag dado.

Asegúrese de implementar un manejo de errores adecuado en su código para gestionar las posibles excepciones.

<Note>
  La variación predeterminada se refiere a la variación asignada a un visitante cuando no coincide con ninguna regla de entrega predefinida para un feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. Se representa como la variación en la sección "Then, for everyone else..." de la interfaz de administración.
</Note>

```php theme={null}
$featureKey = "new_checkout";

try {
    $variation = $kameleoonClient->getVariation($visitorCode, $featureKey);
    // disabling tracking
    $variation = $kameleoonClient->getVariation($visitorCode, $featureKey, false);
} catch (Kameleoon\Exception\FeatureNotFound $e) {
    // An error has occurred; the feature flag isn't found in the current configuration.
} catch (Kameleoon\Exception\FeatureEnvironmentDisabled $e) {
    // The feature flag is disabled for the environment.
} catch (Kameleoon\Exception\VisitorCodeInvalid $e) {
    // The visitor code you passed to the method is invalid and can't be accepted by the SDK.
}

// Fetch a variable value for the assigned variation
$title = $variation->variables["title"]->value;

switch ($variation->key) {
    case "on":
        // Main variation key is selected for visitorCode
        break;
    case "alternative_variation":
        // Alternative variation key
        break;
    default:
        // Default variation key
        break;
}
```

##### Argumentos

| Name                        | Type     | Description                                                                                           | Default |
| --------------------------- | -------- | ----------------------------------------------------------------------------------------------------- | ------- |
| visitorCode (*obligatorio*) | `string` | Identificador único del visitante.                                                                    |         |
| featureKey (*obligatorio*)  | `string` | Clave de la funcionalidad que desea exponer a un visitante.                                           |         |
| track (*opcional*)          | `bool`   | Parámetro opcional para habilitar o deshabilitar el seguimiento de la evaluación de la funcionalidad. | `true`  |

##### Valor de retorno

| Tipo        | Descripción                                                                           |
| ----------- | ------------------------------------------------------------------------------------- |
| `Variation` | An assigned [`Variation`](#variation) to a given visitor for a specific feature flag. |

##### Excepciones lanzadas

| Tipo                         | Descripción                                                                                                                                                                                                                                                                                      |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `VisitorCodeInvalid`         | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters.                                                                                                                                                                           |
| `FeatureNotFound`            | Excepción que indica que la clave de funcionalidad solicitada no se encontró en la configuración interna del SDK. Esto suele significar que el feature flag no está activado en la aplicación de Kameleoon (pero el código que implementa la funcionalidad ya está desplegado en la aplicación). |
| `FeatureEnvironmentDisabled` | Excepción que indica que el feature flag está deshabilitado para el entorno actual del visitante (por ejemplo, production, staging o development).                                                                                                                                               |

#### getVariations()

* 📨 *Envía datos de seguimiento a Kameleoon (dependiendo del parámetro `track`)*

Recupera un map de objetos [`Variation`](#variation) asignados a un visitante dado para todos los feature flags.

Este método itera sobre todos los feature flags disponibles y devuelve la `Variation` asignada para cada flag asociado con el visitante especificado. It takes `visitorCode` as a mandatory argument, while `onlyActive` and `track` are optional.

* Si `onlyActive` se establece en `true`, el método `getVariations()` devolverá las variaciones de los feature flags siempre que el usuario no esté asignado a la variación `off`.
* El parámetro `track` controla si el método realizará el seguimiento de las asignaciones de variación. De forma predeterminada, it is set to `true`. Si se establece en `false`, el seguimiento estará deshabilitado.

El map devuelto consta de claves de feature flags como claves y su `Variation` correspondiente como valores. Si no se asigna ninguna variación para un feature flag, el método devuelve la `Variation` predeterminada para ese flag.

Se debe implementar un manejo de errores adecuado para gestionar las posibles excepciones.

<Note>
  La variación predeterminada se refiere a la variación asignada a un visitante cuando no coincide con ninguna regla de entrega predefinida para un feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. Se representa como la variación en la sección "Then, for everyone else..." de la interfaz de administración.
</Note>

```php theme={null}
try {
    $variations = $kameleoonClient->getVariations($visitorCode);
    // only active variations
    $variations = $kameleoonClient->getVariations($visitorCode, true);
    // disable tracking
    $variations = $kameleoonClient->getVariations($visitorCode, $onlyActive, false);
} catch (Kameleoon\Exception\VisitorCodeInvalid $e) {
    // Handle exception
}
```

##### Argumentos

| Name                        | Type     | Description                                                                                                                   | Default |
| --------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------- | ------- |
| visitorCode (*obligatorio*) | `string` | Identificador único del visitante.                                                                                            |         |
| onlyActive (*opcional*)     | `bool`   | Parámetro opcional que indica si se deben devolver las variaciones para los feature flags activos (`true`) o todos (`false`). | `false` |
| track (*opcional*)          | `bool`   | Parámetro opcional para habilitar o deshabilitar el seguimiento de la evaluación de la funcionalidad.                         | `true`  |

##### Valor de retorno

| Tipo                             | Descripción                                                                                                                                          |
| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `array<string, Types\Variation>` | Map que contiene los objetos [`Variation`](#variation) asignados de los feature flags utilizando las claves de las funcionalidades correspondientes. |

##### Excepciones lanzadas

| Tipo                 | Descripción                                                                                                            |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `VisitorCodeInvalid` | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |

#### setForcedVariation()

El método permite you to programmatically assign a specific [`Variation`](#variation) to a user, bypassing the standard evaluation process. Esto es especialmente valioso para experimentos controlados donde la lógica de evaluación habitual no es necesaria o debe omitirse. It can also be helpful in scenarios like debugging or custom testing.

Cuando se establece una variación **forzada**, esta anula la lógica de evaluación en tiempo real de Kameleoon. Processes like segmentation, targeting conditions, and algorithmic calculations are skipped. To preserve segmentation and targeting conditions during an experiment, set `forceTargeting=false` instead.

<Info>
  **Simulated** variations always take precedence in the execution order. If a **simulated** variation calculation is triggered, it will be fully processed and completed first.
</Info>

A forced variation is treated the same as an evaluated variation. It is tracked in analytics and stored in the user context like any standard evaluated variation, ensuring consistency in reporting.

El método puede lanzar excepciones bajo ciertas condiciones (por ejemplo, parámetros no válidos, contexto del usuario o problemas internos). Proper exception handling is essential to ensure that your application remains stable and resilient.

<Warning>
  It’s important to distinguish **forced** variations from **[simulated](#getvisitorcode)** variations:

  * **Forced variations**: Are specific to an individual experiment.
  * **Simulated variations**: Affect the overall **feature flag** result.
</Warning>

```php theme={null}
$experimentId = 9516;
try {
    // Forcing the variation "on" for the experiment 9516 for the visitor
    $kameleoonClient->setForcedVariation($visitorCode, $experimentId, "on");

    // Forcing the variation "on" while preserving segmentation and targeting conditions during the experiment
    $kameleoonClient->setForcedVariation($visitorCode, $experimentId, "on", false);

    // Resetting the forced variation for the experiment 9516 for the visitor
    $kameleoonClient->setForcedVariation($visitorCode, $experimentId, null);
} catch (Kameleoon\Exception\KameleoonException $e) {
    // Handling the error
}
```

##### Argumentos

| Name                         | Type      | Description                                                                                                                                                                                                                                                   | Default |
| ---------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| visitorCode (*obligatorio*)  | `string`  | Identificador único del visitante.                                                                                                                                                                                                                            |         |
| experimentId (*obligatorio*) | `int`     | **Experiment Id** que será segmentado y seleccionado durante el proceso de evaluación.                                                                                                                                                                        |         |
| variationKey (*obligatorio*) | `?string` | **Variation Key** correspondiente a una `Variation` que debe forzarse como valor devuelto para el experimento. Si el valor es `null`, la variación forzada se restablecerá.                                                                                   |         |
| forceTargeting (*opcional*)  | `bool`    | Indica si la segmentación para el experimento debe forzarse y omitirse (`true`) o aplicarse como en el proceso de evaluación estándar (`false`).                                                                                                              | `true`  |
| timeout (*opcional*)         | `?int`    | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. If a timeout value is not provided, the SDK uses the [`default_timeout`](#configuración-adicional) specified in your configuration. | `null`  |

##### Excepciones lanzadas

| Tipo                        | Descripción                                                                                                                                                                                                                                             |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `VisitorCodeInvalid`        | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters.                                                                                                                                  |
| `FeatureExperimentNotFound` | Excepción que indica que el experiment id solicitado no se encontró en la configuración interna del SDK. Esto suele ser normal y significa que el experimento correspondiente a la regla todavía no se ha activado del lado de Kameleoon.               |
| `FeatureVariationNotFound`  | Excepción que indica que la variation key (id) solicitada no se ha encontrado en la configuración interna del SDK. Esto suele ser normal y significa que el experimento correspondiente a la variación todavía no se ha activado del lado de Kameleoon. |

<Info>
  En la mayoría de los casos, solo es necesario gestionar el error básico `KameleoonException`, como se muestra en el ejemplo. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including `Exception`.
</Info>

#### evaluateAudiences()

* 📨 *Envía datos de seguimiento a Kameleoon*

Este método evalúa a los visitantes con respecto a todos los segmentos disponibles de Audiences Explorer y realiza el seguimiento de los que coinciden.

`evaluateAudiences()` should be called **after all relevant visitor data has been set or updated**, and **just before** getting a feature variation or checking a feature flag. Este enfoque garantiza que el visitante se evalúe con los datos más recientes disponibles, lo que permite una asignación precisa de audiencia basada en todos los criterios.

After calling this method, you can perform a detailed analysis of segment performance in Audiences Explorer.

```php theme={null}
try {
    $kameleoonClient->evaluateAudiences($visitorCode);
} catch (Kameleoon\Exception\KameleoonException $e) {
    // Handling the exception
}
```

##### Argumentos

| Nombre                      | Tipo     | Descripción                                                                                                                                                                                                                                                   | Default |
| --------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| visitorCode (*obligatorio*) | `string` | Identificador único del visitante.                                                                                                                                                                                                                            |         |
| timeout (*opcional*)        | `?int`   | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. If a timeout value is not provided, the SDK uses the [`default_timeout`](#configuración-adicional) specified in your configuration. | `null`  |

##### Excepciones lanzadas

| Tipo                 | Descripción                                                                                                            |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `VisitorCodeInvalid` | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |

<Info>
  En la mayoría de los casos, solo es necesario gestionar el error básico `KameleoonException`, como se muestra en el ejemplo. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including `Exception`.
</Info>

#### getDataFile()

<Tip>
  To evaluate all feature flags, use [`getVariations()`](#getvariations). Este método es más eficiente que llamar a `DataFile` e iterar por los flags con [`getVariation()`](#getvariation).
</Tip>

Devuelve la configuración actual del SDK como un objeto [`DataFile`](#datafile).

```php theme={null}
try {
    $dataFile = $kameleoonClient->getDataFile();
} catch (Kameleoon\Exception\KameleoonException $e) {
    // Recommended (but optional) safeguard for unexpected exceptions from third-party libraries
}
```

##### Argumentos

| Nombre               | Tipo   | Descripción                                                                                                                                                                                                                                                   |
| -------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| timeout (*opcional*) | `?int` | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. If a timeout value is not provided, the SDK uses the [`default_timeout`](#configuración-adicional) specified in your configuration. |

##### Valor de retorno

| Tipo       | Descripción                                                      |
| ---------- | ---------------------------------------------------------------- |
| `DataFile` | El [`DataFile`](#datafile) que contiene la configuración del SDK |

### Datos del visitante

#### getVisitorCode()

<Note>
  Este método se llamaba anteriormente `obtainVisitorCode`, que fue eliminado en la versión `4.0.0` del SDK.
</Note>

Llame a este método para obtener el **visitorCode** de Kameleoon del visitante actual. Llamarlo es especialmente importante al utilizar Kameleoon en un entorno mixto de front-end y back-end, donde se debe garantizar la consistencia en la identificación del usuario. La lógica de implementación se describe a continuación:

1. First, we check if there is a **kameleoonVisitorCode** cookie or query parameter associated with the current Solicitud HTTP. If so, we use this as the visitor identifier.

2. If no cookie or parameter is present in the current request, we have two options for generating an identifier. One option is to create a new identifier randomly, and the other is to use the **defaultVisitorCode** argument if it has been provided. This feature allows our customers to input their own identifiers as visitor codes, which can be beneficial; it seamlessly matches Kameleoon visitors with their own users, eliminating the need for extra look-ups in a matching table.

3. In any case, the server-side (via HTTP header) **kameleoonVisitorCode** cookie is set with the value. El método devuelve this visitor value.

Para más información, consulte [este artículo](/developer-docs/feature-experimentation/get-started/hybrid-experimentation/).

<Note>
  If you provide your own `visitorCode`, its uniqueness must be guaranteed on your end - the SDK cannot check it. Also note that the length of `visitorCode` is limited to **255** characters. Any excess characters will throw an exception.
</Note>

<Info>
  El método `getVisitorCode()` le permite establecer variaciones **simuladas** para un visitante. Cuando las cookies (de una **request** o **document**) contienen la clave `kameleoonSimulationFFData`, se omite el proceso de evaluación estándar. En su lugar, el método devuelve directamente una [`Variation`](#variation) basada en los datos proporcionados.

  Puede aplicar simulaciones de dos formas:

  * **Automatically (recommended):** If using Kameleoon Web Experimentation or the SDK in [Hybrid mode](/developer-docs/feature-experimentation/get-started/hybrid-experimentation#linking-feature-experiments-with-front-end-tracking-code), the cookie is created automatically when simulating a variant's display using the [Simulation Panel](/user-manual/experimentation/feature-experimentation/using-the-rollout-planner/validation-and-rollback/using-simulation-mode).
  * **Manualmente:** Establezca la cookie `kameleoonSimulationFFData` manualmente.

  It’s important to distinguish **simulated** variations from **[forced](#setforcedvariation)** variations:

  * **Simulated variations**: Affect the overall **feature flag** result.
  * **Forced variations**: Are specific to an individual experiment.

  ⚙️ **Manual setup**

  Asegúrese de que la cookie `kameleoonSimulationFFData` siga este formato:

  * `kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}`: Simula la variación con `varId` del experimento `expId` para el `featureKey` indicado.
  * `kameleoonSimulationFFData={"featureKey":{"expId":0}}`: Simula la variación predeterminada (definida en la sección **Then, for everyone else in Production, serve**) para el `featureKey` indicado.

  ⚠️ To ensure proper functionality, the cookie value must be encoded as a URI component using a method such as [`encodeURIComponent`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent).
</Info>

```php theme={null}
require "vendor/autoload.php";

// The cookie's domain must be provided in the configuration file if no argument is given.

$visitorCode = $kameleoonClient->getVisitorCode();

// default visitor code provided
$visitorCode = $kameleoonClient->getVisitorCode($defaultVisitorCode);
```

##### Argumentos

| Nombre             | Tipo   | Descripción                                                                                                                                                                                                                                                                           |
| ------------------ | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| defaultVisitorCode | String | This parameter will be used as the **visitorCode** if no existing **kameleoonVisitorCode** cookie is found on the request. This field is optional, and, by default, a random **visitorCode** will be generated.                                                                       |
| timeout            | ?int   | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the [`default_timeout`](#configuración-adicional) specified in your configuration. |

##### Valor de retorno

| Tipo   | Descripción                                                                                                                 |
| ------ | --------------------------------------------------------------------------------------------------------------------------- |
| String | A **visitorCode** that will be associated with this particular user and should be used with most of the methods of the SDK. |

##### Excepciones lanzadas

| Type                     | Description                                                                                                                                                      |
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| InvalidArgumentException | Exception indicating that the cookie's domain value was not provided (either via the configuration file, or via the **topLevelDomain** parameter on the method). |

#### addData()

El método `addData()` añade [datos de segmentación](#tipos-de-datos) al almacenamiento para que otros métodos puedan utilizar los datos para decidir si segmentar o no al visitante actual.

El método `addData()` no devuelve ningún valor y no interactúa por sí mismo con los servidores backend de Kameleoon. En su lugar, todos los datos declarados se guardan para su transmisión futura mediante el método [`flush()`](#flush). Este enfoque reduce el número de llamadas al servidor, ya que los datos se agrupan habitualmente en una única llamada al servidor que desencadena el `flush()`.

El método [`trackConversion()`](#trackconversion) también envía cualquier dato previamente asociado, al igual que `flush()`. The same holds true for [`getVariation()`](#getvariation) and [`getVariations()`](#getvariations) methods if an experimentation rule is triggered.

<Tip>
  Cada visitante solo puede tener una instancia de datos asociados para la mayoría de los tipos de datos. However, [`CustomData`](#customdata) is an exception. Visitors can have one instance of associated `CustomData` per index.
</Tip>

```php theme={null}
// Add a single data item (tracked by default)
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Browser(Kameleoon\Data\Browser::CHROME));

// Add multiple data items (tracked by default)
$kameleoonClient->addData(
    $visitorCode,
    new Kameleoon\Data\PageView("https://url.com", "title", [3]),
    new Kameleoon\Data\UserAgent("UserAgent")
);

// Add multiple data items stored locally for targeting only (not sent to the Kameleoon Data API)
$kameleoonClient->addData(
    $visitorCode,
    false,
    new Kameleoon\Data\PageView("https://url.com", "title", [3]),
    new Kameleoon\Data\UserAgent("UserAgent")
);
```

##### Argumentos

| Nombre                      | Tipo      | Descripción                                                                                                                                                                                                                       | Valor predeterminado |
| --------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- |
| visitorCode (*obligatorio*) | `string`  | Identificador único del visitante.                                                                                                                                                                                                |                      |
| track (*opcional*)          | `bool`    | Especifica si los datos añadidos son aptos para el seguimiento. Cuando se establece en `false`, los datos se almacenan localmente y se utilizan solo para la evaluación de segmentación; no se envían a la Data API de Kameleoon. | `true`               |
| data (*obligatorio*)        | `...Data` | Colección de tipos de datos de Kameleoon.                                                                                                                                                                                         |                      |

##### Excepciones

| Tipo                 | Descripción                                                                                                            |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `VisitorCodeInvalid` | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |

#### flush()

* 📨 *Envía datos de seguimiento a Kameleoon*

The `flush()` method is responsible for sending the Kameleoon data linked to a specific visitor. It triggers a tracking request that includes all the data previously added with the `addData` method, which has not yet been sent during an earlier call to [one of the methods](/developer-docs/feature-experimentation/technical-reference/faq-global#when-does-the-sdk-send-a-tracking-request-for-analytics). `flush()` is non-blocking, as the server call is made asynchronously, unless the `instant` parameter is set to `true`.

La función `flush()` le permite decidir cuándo se envían a nuestros servidores los datos vinculados a un `visitorCode` específico. Por ejemplo, si llama a `addData()` varias veces, digamos una docena, sería ineficiente enviar datos al servidor cada vez que realiza una llamada. En su lugar, puede recopilar todos los datos primero y luego llamar a `flush()` una sola vez al final para enviarlos todos a la vez.

Si especifica un `visitorCode`, el método `flush()` lo usa como identificador único del visitante, lo cual es útil para la [experimentación entre dispositivos](/developer-docs/cross-device-experimentation). Cuando especifica un `visitorCode` y establece el parámetro `isUniqueIdentifier` en `true`, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.

<Note>
  El parámetro `isUniqueIdentifier` está obsoleto. Utilice en su lugar [`UniqueIdentifier`](#uniqueidentifier).

  `isUniqueIdentifier` puede ser útil en situaciones particulares; por ejemplo, si no puede acceder al `visitorCode` anónimo asignado a un visitante, pero puede usar un ID interno vinculado a ese visitante a través de la fusión de sesiones.
</Note>

```php theme={null}
$visitorCode = $kameleoonClient->getVisitorCode();

$kameleoonClient->addData(
    $visitorCode,
    new Kameleoon\Data\Browser(Kameleoon\Data\Browser::CHROME).
    new Kameleoon\Data\PageView("https://url.com", "title", array(3)),
    new Kameleoon\Data\Conversion(32, 10, false)
);

$kameleoonClient->flush($visitorCode); // Interval tracking, non-blocking operation

$kameleoonClient->flush($visitorCode, null, null, true); // Instant tracking, blocking operation

// if you operate with unique ID
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\UniqueIdentifier(true));
$kameleoonClient->flush($visitorCode);
```

##### Argumentos

| Nombre                        | Tipo   | Descripción                                                                                                                                                                                                                                                                           |
| ----------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorCode                   | string | Identificador único del usuario. Este campo es obligatorio.                                                                                                                                                                                                                           |
| timeout                       | ?int   | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the [`default_timeout`](#configuración-adicional) specified in your configuration. |
| isUniqueIdentifier (Obsoleto) | ?bool  | Parámetro opcional para indicar si el visitorCode es un identificador único. If not provided, el valor predeterminado es `null`. The field is optional.                                                                                                                               |
| instant                       | bool   | Boolean flag indicating whether the data should be sent instantly (`true`) or according to the scheduled tracking interval (`false`). If not provided, el valor predeterminado es `false`. Este campo es opcional.                                                                    |

#### getRemoteData()

<Note>
  Este método se llamaba anteriormente `retrieveDataFromRemoteSource`, que fue eliminado en la versión `4.0.0` del SDK.
</Note>

The `getRemoteData()` method lets you retrieve data based on a **key** you provide for a specific **siteCode** (set in `KameleoonClientFactory.create()`). A Kameleoon server stores this data. The Data API is typically used to save this data on our remote servers. This method, combined with our scalable servers, makes storing large amounts of data easy. You can then access this data later for each visitor or user.

```php theme={null}
$test_value = $kameleoonClient->getRemoteData("test"); // default timeout will be used

$test_value = $kameleoonClient->getRemoteData("test", 1000); // 1000 milliseconds timeout

try {
    $test_value = $kameleoonClient->getRemoteData("test");
} catch (Exception $e) {
    // Timeout or Json Decoding Exception
}
```

##### Argumentos

| Nombre  | Tipo   | Descripción                                                                                                                                                                                                                                                                           |
| ------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| key     | string | The key that the data you try to get is associated with. Este campo es obligatorio.                                                                                                                                                                                                   |
| timeout | ?int   | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the [`default_timeout`](#configuración-adicional) specified in your configuration. |

##### Valor de retorno

| Tipo   | Descripción                                                  |
| ------ | ------------------------------------------------------------ |
| Object | Object associated with retrieving data for specific **key**. |

##### Excepciones lanzadas

| Tipo      | Descripción                                                                                                   |
| --------- | ------------------------------------------------------------------------------------------------------------- |
| Exception | Exception indicating that the request timed out or retrieved data can't be decoded with `json_decode` method. |

#### getRemoteVisitorData()

`getRemoteVisitorData()` es un método asíncrono para recuperar los datos de visitas de Kameleoon para el `visitorCode` desde la Data API de Kameleoon. El método añade data to storage for other methods to use when making targeting decisions.

Los datos obtenidos mediante este método desempeñan un papel importante cuando desea:

* use data collected from other devices.
* access a user's history, such as previously visited pages during past visits.
* use data that is only accessible on the client-side, like datalayer variables and goals that only convert on the front-end.

Read [this article](/developer-docs/feature-experimentation/targeting-and-segmentation/native-segmentation) for a better understanding of possible use cases.

<Warning>
  De forma predeterminada, `getRemoteVisitorData()` automatically retrieves the latest stored custom data with `scope=Visitor` and attaches them to the visitor without the need to call the method `addData()`. It is particularly useful for [synchronizing custom data between multiple devices](/developer-docs/sdks/web-sdks/nodejs-sdk#synchronizing-custom-data-across-devices).
</Warning>

<Note>
  El parámetro `isUniqueIdentifier` está obsoleto. Utilice en su lugar [`UniqueIdentifier`](#uniqueidentifier).

  `isUniqueIdentifier` puede ser útil en situaciones particulares; por ejemplo, si no puede acceder al `visitorCode` anónimo asignado a un visitante, pero puede usar un ID interno vinculado a ese visitante a través de la fusión de sesiones.
</Note>

```php theme={null}
$visitorCode = "visitorCode";

// Visitor data will be fetched and automatically added for `visitorCode`
$dataArray = $kameleoonClient->getRemoteVisitorData($visitorCode, null); // default timeout will be used
$dataArray = $kameleoonClient->getRemoteVisitorData($visitorCode, 1000); // 1000 milliseconds timeout

// If you only want to fetch data and add it yourself manually, set shouldAddData == `false`
$dataArray = $kameleoonClient->getRemoteVisitorData($visitorCode, null, false); // default timeout will be used
$dataArray = $kameleoonClient->getRemoteVisitorData($visitorCode, 1000, false); // 1000 milliseconds timeout
```

##### Argumentos

| Nombre                        | Tipo                                      | Descripción                                                                                                                                                                                                                                                                                                   |
| ----------------------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorCode                   | `string`                                  | The visitor code for which you want to retrieve the assigned data. Este campo es obligatorio.                                                                                                                                                                                                                 |
| timeout                       | `?int`                                    | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the [`default_timeout`](#configuración-adicional) specified in your configuration.                         |
| addData                       | `bool`                                    | Booleano que indica si el método debe añadir automáticamente los datos recuperados para un visitante. If not specified, el valor predeterminado es **true**. Este campo es opcional.                                                                                                                          |
| filter                        | `Kameleoon\Types\RemoteVisitorDataFilter` | Filter for specifying what data should be retrieved from visits, by default only `CustomData` is retrieved from the current and latest previous visit (`new RemoteVisitorDataFilter(1, true, true)` or `new RemoteVisitorDataFilter()`). Other filters parameters are set to `false`. This filed is optional. |
| isUniqueIdentifier (Obsoleto) | `?bool`                                   | Parámetro opcional para indicar si el visitorCode es un identificador único. If not provided, el valor predeterminado es `null`. The field is optional.                                                                                                                                                       |

##### Valor de retorno

| Tipo                    | Descripción                                   |
| ----------------------- | --------------------------------------------- |
| `array<Kameleoon\Data>` | A list of data assigned to the given visitor. |

##### Uso de parámetros en getRemoteVisitorData()

El método `getRemoteVisitorData()` ofrece flexibilidad al permitirle definir varios parámetros al recuperar datos de los visitantes. Whether you're targeting based on goals, experiments, or variations, the same approach applies across all data types.

Por ejemplo, let's say you want to retrieve data on visitors who completed a goal "Order transaction". Puede especificar parámetros dentro del método `getRemoteVisitorData()` para refinar su segmentación. For instance, if you want to target only users who converted on the goal in their last five visits, you can set the `previousVisitAmount` parameter to 5 and `conversions` to true.

La flexibilidad mostrada en este ejemplo no se limita a los datos de objetivos. Puede usar parámetros dentro del método `getRemoteVisitorData()` para recuperar datos sobre una variedad de comportamientos del visitante.

<Note>
  Here is the list of available `Kameleoon\Types\RemoteVisitorDataFilter` options:

  | Name                             | Type   | Description                                                                                                                                                                                                                                                                                                                                     | Default |
  | -------------------------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
  | previousVisitAmount (*opcional*) | `int`  | Número de visitas previas de las que recuperar datos. Number between `1` and `25`                                                                                                                                                                                                                                                               | `1`     |
  | currentVisit (*opcional*)        | `bool` | If true, current visit data will be retrieved                                                                                                                                                                                                                                                                                                   | `true`  |
  | customData (*opcional*)          | `bool` | If true, custom data will be retrieved.                                                                                                                                                                                                                                                                                                         | `true`  |
  | pageViews (*opcional*)           | `bool` | If true, page data will be retrieved.                                                                                                                                                                                                                                                                                                           | `false` |
  | geolocation (*opcional*)         | `bool` | If true, geolocation data will be retrieved.                                                                                                                                                                                                                                                                                                    | `false` |
  | device (*opcional*)              | `bool` | If true, device data will be retrieved.                                                                                                                                                                                                                                                                                                         | `false` |
  | browser (*opcional*)             | `bool` | If true, browser data will be retrieved.                                                                                                                                                                                                                                                                                                        | `false` |
  | operatingSystem (*opcional*)     | `bool` | If true, operating system data will be retrieved.                                                                                                                                                                                                                                                                                               | `false` |
  | conversions (*opcional*)         | `bool` | If true, conversion data will be retrieved.                                                                                                                                                                                                                                                                                                     | `false` |
  | experiments (*opcional*)         | `bool` | If true, experiment data will be retrieved.                                                                                                                                                                                                                                                                                                     | `false` |
  | kcs (*opcional*)                 | `bool` | If true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the [AI Predictive Targeting add-on](/user-manual/ai-predictive-targeting/target-users-based-on-likelihood-to-convert)                                                                                                                                                    | `false` |
  | visitorCode (*opcional*)         | `bool` | If true, Kameleoon will retrieve the `visitorCode` from the most recent visit and use it for the current visit. This is necessary if you want to ensure that the visitor, identified by their `visitorCode`, always receives the same variation across visits for [Cross-device experimentation](/developer-docs/cross-device-experimentation). | `true`  |
  | cbs (*opcional*)                 | `bool` | If true, Contextual Bandit score data will be retrieved.                                                                                                                                                                                                                                                                                        | `false` |
  | personalization (*opcional*)     | `bool` | If true, personalization data will be retrieved. This is required for the personalization condition.                                                                                                                                                                                                                                            | `false` |
</Note>

#### getVisitorWarehouseAudience()

Este método recupera all audience data associated with the visitor in your data warehouse using the specified `visitorCode` and `warehouseKey`. The `warehouseKey` is typically your internal user ID. The `customDataIndex` parameter corresponds to the Kameleoon custom data that Kameleoon uses to target your visitors. You can refer to the [warehouse targeting documentation](/user-manual/integrations/data-warehouses/bigquery/use-bigquery-as-a-source-audience-targeting) for additional details. The method passes the result to the returned future as a `CustomData` object, confirming that the data has been added to the visitor and is available for targeting purposes.

```php theme={null}
$warehouseAudienceCustomData = $kameleoonClient->getVisitorWarehouseAudience($visitorCode, $customDataIndex);

// If you need to specify warehouse key
$warehouseAudienceCustomData = $kameleoonClient->getVisitorWarehouseAudience(
    $visitorCode, $customDataIndex, $warehouseKeyValue
);

// If you need to specify warehouse key & timeout
$warehouseAudienceCustomData = $kameleoonClient->getVisitorWarehouseAudience(
    $visitorCode, $customDataIndex, $warehouseKeyValue, 2000
);
```

##### Argumentos

| Nombre          | Tipo   | Descripción                                                                                                                                                                                                                                                                           |
| --------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorCode     | string | The unique identifier of the visitor for whom you want to retrieve and add the data.                                                                                                                                                                                                  |
| customDataIndex | int    | Entero que representa el índice del dato personalizado que desea utilizar para segmentar sus BigQuery Audiences.                                                                                                                                                                      |
| warehouseKey    | string | The unique key to identify the warehouse data (usually, your internal user ID). Este campo es opcional.                                                                                                                                                                               |
| timeout         | ?int   | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the [`default_timeout`](#configuración-adicional) specified in your configuration. |

##### Valor de retorno

| Tipo          | Descripción                                                                                                                                                           |
| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `?Customdata` | `CustomData` instance confirming that the data has been added to the visitor. If value is `null`, the request is failed and `CustomData` wasn't added to the visitor. |

##### Excepciones lanzadas

| Type                 | Description                                                                                                     |
| -------------------- | --------------------------------------------------------------------------------------------------------------- |
| `VisitorCodeInvalid` | Excepción que indica que el visitor code proporcionado no es válido (está vacío o tiene más de 255 caracteres). |

#### setLegalConsent()

You must use this method to specify whether the visitor has given legal consent to use thier personal data. Setting the `legalConsent` parameter to `false` limits the types of data that you can include in tracking requests. This method helps you adhere to legal and regulatory requirements while responsibly managing visitor data. You can find more information on personal data in the [consent management policy](/user-manual/project-management/consent-management-policy).

```php theme={null}
$visitorCode = $kameleoonClient->getVisitorCode();
$kameleoonClient->setLegalConsent($visitorCode, true);
```

##### Argumentos

| Nombre       | Tipo   | Descripción                                                                                                                                                                                                                           |
| ------------ | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorCode  | string | Identificador único del usuario. Este campo es obligatorio.                                                                                                                                                                           |
| legalConsent | bool   | Valor booleano que representa el estado del consentimiento legal. `true` indicates the visitor has given legal consent, `false` indicates the visitor has never provided, or has withdrawn, legal consent. Este campo es obligatorio. |

##### Excepciones lanzadas

| Type               | Description                                                                                              |
| ------------------ | -------------------------------------------------------------------------------------------------------- |
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters). |

##### Comportamiento al revocar el consentimiento

Cuando llama a `setLegalConsent()` con `legalConsent=false`, el SDK no elimina la cookie `kameleoonVisitorCode`. En su lugar, deja de prorrogar la fecha de expiración de la cookie, permitiendo que esta persista hasta que expire de forma natural.

Si sus requisitos de cumplimiento exigen la eliminación inmediata del archivo de cookie al revocar el consentimiento, debe eliminarlo manualmente utilizando los métodos nativos de gestión de cookies de su framework. El SDK no eliminará el archivo automáticamente.

### Goals and third party analytics

#### getEngineTrackingCode()

Kameleoon integrates with several analytics solutions, including Mixpanel, Google Analytics 4, and Segment. To track server-side experiments correctly, call the `getEngineTrackingCode()` method after the visitor triggers an experiment. The SDK returns JavaScript queue commands for the experiments that the visitor triggered during the previous five seconds. When you insert this code into the page, Engine.js processes the commands and sends the exposure events through the active analytics integration.

Consulte [experimentación híbrida](/developer-docs/feature-experimentation/get-started/hybrid-experimentation) para más información sobre cómo implementar este método.

```php theme={null}
$engineTrackingCode = $kameleoonClient->getEngineTrackingCode($visitorCode);
```

<Note>
  * To use this feature, implement both the PHP SDK and Kameleoon [Engine.js](/developer-docs/web-experimentation/implementation-and-deployment/standard-implementation). Because Engine.js is used only for tracking in this flow, you can install the asynchronous tag before the closing `</body>` tag.
  * If you only want to track experiments in Kameleoon and do not need to send exposure events to third-party analytics tools, use the [JavaScript / TypeScript SDK](/developer-docs/sdks/web-sdks/js-sdk). This option works well for [serverless edge compute platforms](/developer-docs/feature-experimentation/implementation-and-deployment/serverless-edge-compute-starter-kits). The JavaScript / TypeScript SDK automatically tracks variations when you call [`getVisitorCode`](/developer-docs/sdks/web-sdks/js-sdk#getvisitorcode), as long as you add the corresponding experiment assignments to `window.kameleoonQueue`..
  * You can insert the returned tracking code directly into an HTML `<script>` tag.

  ```html theme={null}
  <html lang="en">
    <body>
      <script>
        const engineTrackingCode = `
          window.kameleoonQueue = window.kameleoonQueue || [];
          window.kameleoonQueue.push(['Experiments.assignVariation', 123456, 7890, true]);
          window.kameleoonQueue.push(['Experiments.trigger', 123456, true]);
          window.kameleoonQueue.push(['Experiments.assignVariation', 234567, 8901, true]);
          window.kameleoonQueue.push(['Experiments.trigger', 234567, true]);
        `;
        const script = document.createElement('script');

        script.textContent = engineTrackingCode;
        document.body.appendChild(script);
      </script>

    </body>
  </html>
  ```

  En este ejemplo, `123456` y `234567` son IDs de experimento, y `7890` y `8901` son IDs de variación. En su implementación, el SDK genera estos valores en el código de seguimiento devuelto.
</Note>

##### Argumentos

| Nombre                      | Tipo     | Descripción                        |
| --------------------------- | -------- | ---------------------------------- |
| visitorCode (*obligatorio*) | `string` | Identificador único del visitante. |

##### Valor de retorno

| Tipo     | Descripción                                   |
| -------- | --------------------------------------------- |
| `string` | Código JavaScript para insertar en la página. |

#### trackConversion()

* 📨 *Envía datos de seguimiento a Kameleoon*

Use este método para track a conversion for a specific [goal](/user-manual//assets/goals/create-a-goal) and user. This method requires `visitorCode` and `goalId`. In addition, this method also accepts an optional `revenue`, `negative` and `metadata` arguments. The `visitorCode` is usually identical to the one that was used when triggering the experiment.

El método `trackConversion()` no devuelve ningún valor. Este método no es bloqueante, ya que la llamada al servidor se realiza de forma asíncrona.

<Note>
  El parámetro `isUniqueIdentifier` está obsoleto. Utilice en su lugar [`UniqueIdentifier`](#uniqueidentifier).

  `isUniqueIdentifier` también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al `visitorCode` anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
</Note>

```php theme={null}
require "vendor/autoload.php";

$kameleoonClient = Kameleoon\KameleoonClientFactory::create("a8st4f59bj", "/tmp/kameleoon/client-php.json");
$visitorCode = $kameleoonClient->getVisitorCode();
$goalID = 83023;

$kameleoonClient->trackConversion($visitorCode, $goalID);

// if you operate with unique ID
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\UniqueIdentifier(true));
$kameleoonClient->trackConversion($visitorCode, $goalID, 0.0);

// Add metadata
$cd = new Kameleoon\Data\CustomData(1, "metadata");
$kameleoonClient->trackConversion($visitorCode, $goalID, 0.0, null, null, false, [$cd]);
```

##### Argumentos

| Nombre                            | Tipo                 | Descripción                                                                                                                                                                                                                                                                                                                                                               | Default |
| --------------------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| visitorCode (*obligatorio*)       | `string`             | Identificador único del visitante.                                                                                                                                                                                                                                                                                                                                        |         |
| goalId (*obligatorio*)            | `int`                | ID del objetivo.                                                                                                                                                                                                                                                                                                                                                          |         |
| revenue (*opcional*)              | `float`              | Ingreso de la conversión.                                                                                                                                                                                                                                                                                                                                                 | `0`     |
| negative (*opcional*)             | `bool`               | Define si el ingreso es positivo o negativo.                                                                                                                                                                                                                                                                                                                              | `false` |
| metadata (*opcional*)             | `?array<CustomData>` | Le permite establecer valores específicos para los datos personalizados que se hayan definido como metadatos del objetivo en la aplicación de Kameleoon. Example: `[CustomData{id: 5, value: "Payment Type"}, CustomData{id: 6, value: "Delivery Method"}]`. In this example, `5` and `9` are the indexes of the custom data (5 = “Payment Type”, 9 = “Delivery Method”). | `null`  |
| isUniqueIdentifier *(deprecated)* | `bool`               | Parámetro opcional para indicar si el visitorCode es un identificador único.                                                                                                                                                                                                                                                                                              | `false` |

<Note>
  metadata values are accessible through [raw data exports](/user-manual/experiment-analytics/analyze-results/results-page/results-page-actions#Export) and [the results page](/user-manual/experiment-analytics/analyze-results/data-and-metrics/goal-metadata).

  Si se proporciona el parámetro `metadata`, Kameleoon utilizará estos valores especificados para la conversión actual en lugar de lo recopilado previamente mediante el método [`addData()`](#adddata). Si se omite el parámetro, Kameleoon utilizará los últimos valores rastreados para esos [`CustomData`](#customdata) antes de la conversión y dentro de la misma visita.

  Kameleoon will only consider the metadata values that are explicitly passed as parameters to the `trackConversion()` method.

  En el siguiente ejemplo, Kameleoon will associate the conversion only with the custom data value explicitly provided as a parameter (here: index 5 with the value 'Amex Credit Card').

  ```php theme={null}
  $kameleoonClient->addData(
      $visitorCode,
      new CustomData(5, "Credit Card"),
      new CustomData(9, "Express Delivery")
  );
  $kameleoonClient->trackConversion($visitorCode, 10, 0.0, null, null, false, [new CustomData(5, "Amex Credit Card")]);
  ```
</Note>

##### Excepciones

| Tipo                 | Descripción                                                                                                            |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `VisitorCodeInvalid` | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |

### Tipos de datos

Puede utilizar los siguientes tipos de datos predefinidos de `Kameleoon\Data`.

#### Browser

El conjunto de datos `Browser` almacenado aquí puede utilizarse para filtrar los informes de experimentación y personalización por cualquier valor asociado a él.

| Nombre                      | Tipo    | Descripción                                                                                     |
| --------------------------- | ------- | ----------------------------------------------------------------------------------------------- |
| browserType (*obligatorio*) | `int`   | List of browsers: `CHROME`, `INTERNET_EXPLORER`, `FIREFOX`, `SAFARI`, `OPERA`, `OTHER`.         |
| version (*opcional*)        | `float` | Version of the browser, floating point number represents major and minor version of the browser |

```php theme={null}
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Browser(Kameleoon\Data\Browser::CHROME));

$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Browser(Kameleoon\Data\Browser::CHROME, 10.0));
```

#### PageView

| Name                   | Type          | Description                                              | Default |
| ---------------------- | ------------- | -------------------------------------------------------- | ------- |
| url (*obligatorio*)    | `string`      | URL of the page viewed. Este campo es obligatorio.       |         |
| title (*obligatorio*)  | `?string`     | Title of the page viewed. Este campo es obligatorio.     | `null`  |
| referrers (*opcional*) | `?array<int>` | Referrers de las páginas vistas. Este campo es opcional. | `null`  |

<Note>
  The index (ID) of the referrer is available in our Back-Office in the Acquisition channel configuration page. Be careful: this index starts at 0, so the first [acquisition channel](/user-manual/assets/advanced-targeting-tools/create-an-acquisition-channel) you create for a given site would have the ID 0, not 1.
</Note>

```php theme={null}
$kameleoonClient->addData(
    $visitorCode,
    new Kameleoon\Data\PageView("https://url.com", "title", [3])
);
```

#### Conversion

El conjunto de datos `Conversion` almacenado aquí puede utilizarse para filtrar los informes de experimentación y personalización por cualquier objetivo asociado a él.

<Tip>
  * Each visitor can have multiple `Conversion` objects.
  * You can find the `goalId` in the Kameleoon app.
</Tip>

| Nombre                 | Tipo                 | Descripción                                  | Default |
| ---------------------- | -------------------- | -------------------------------------------- | ------- |
| goalId (*obligatorio*) | `int`                | ID del objetivo.                             |         |
| revenue (*opcional*)   | `float`              | Revenue of the conversion                    | `0`     |
| negative (*opcional*)  | `bool`               | Define si el ingreso es positivo o negativo. | `false` |
| metadata (*opcional*)  | `?array<CustomData>` | Metadatos de la conversión.                  | `null`  |

```php theme={null}
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Conversion(32, 10, false));

$cd = new Kameleoon\Data\CustomData(1, "metadata");
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Conversion(32, 0.0, false, [$cd]));
```

#### CustomData

`CustomData` allows any type of data to be easily associated with each visitor. It can then be used as a targeting condition in [segments](/user-manual/assets/segments/create-a-segment/) or as a filter/breakdown in experiment reports.
To learn more about custom data, please refer to this [article](/developer-docs/custom-data).

| Nombre                      | Tipo           | Descripción                                                                                                                                                                                          | Default |
| --------------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| indexOrName (*obligatorio*) | `int`/`string` | Índice o nombre del dato personalizado. **Either `index` or `name` must be provided** to identify the data.                                                                                          |         |
| values (*obligatorio*)      | `string...`    | Value(s) of the custom data to be stored.                                                                                                                                                            |         |
| overwrite (*opcional*)      | `bool`         | Flag para controlar explícitamente cómo se almacenan los valores y cómo aparecen en los informes. [See more](/developer-docs/custom-data#default-logic-when-overwrite-parameter-is-false-or-omitted) | `true`  |

<Note>
  * Each visitor is allowed only one `CustomData` for each unique `index`. Adding another `CustomData` with the same `index` will replace the existing one.

  * The custom data ‘index’ can be found in the [Custom Data dashboard](/user-manual/assets/custom-data/manage-custom-data) under the “INDEX” column.

  * To prevent the SDK from sending data with the selected index to Kameleoon servers for privacy reasons, enable the option: **Use this data only locally for targeting purposes** when creating custom data.

  * Adding a `CustomData` instance created with a name when the SDK instance configuration is not up to date or the name is not registered, will result in the data being ignored.
</Note>

```php theme={null}
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\CustomData(1, "value"));

// With several values
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\CustomData(1, "value1", "value2"));

// To set the 'overwrite' flag to false
$kameleoonClient->addData($visitorCode, Kameleoon\Data\CustomData::newWithOverwrite(1, false, "value"));

// To use a name instead of the index
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\CustomData("my-custom-data", "value"));

// To use a name instead of the index
// and set the 'overwrite' flag to false
$kameleoonClient->addData($visitorCode, Kameleoon\Data\CustomData::newWithOverwrite("my-custom-data", false, "value"));
```

#### Device

| Nombre | Tipo | Descripción                                                         |
| ------ | ---- | ------------------------------------------------------------------- |
| type   | int  | List of devices: PHONE, TABLET, DESKTOP. Este campo es obligatorio. |

```php theme={null}
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Device(Kameleoon\Data\Device::PHONE));
```

#### UserAgent

Keep track of visitors' user-agent information. Server-side experiments are more likely to be affected by bot traffic than client-side experiments. Kameleoon uses the IAB/ABC International Spiders and Bots List to tackle this issue and recognize known bots and spiders. Kameleoon also uses the `UserAgent` field to filter out bots and other unwanted traffic that might distort your conversion metrics. Para más detalles, consulte our help article on [bot filtering](/user-manual/faq#how-does-kameleoon-filter-bot-traffic-from-my-results).

Si utiliza bots internos, le sugerimos pasar el valor **curl/8.0** del userAgent para excluirlos de nuestra analítica.

| Nombre | Tipo   | Descripción                                                                               |
| ------ | ------ | ----------------------------------------------------------------------------------------- |
| value  | string | The User-Agent value that will be sent with tracking requests. Este campo es obligatorio. |

```php theme={null}
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\UserAgent("TestUserAgent"));
```

#### UniqueIdentifier

Si no añade `UniqueIdentifier` para un visitante, se utiliza `visitorCode` como identificador único del visitante, lo cual es útil para la [experimentación entre dispositivos](/developer-docs/cross-device-experimentation). Cuando añade `UniqueIdentifier` para un visitante, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.

`isUniqueIdentifier` puede ser útil en situaciones particulares; por ejemplo, si no puede acceder al `visitorCode` anónimo asignado a un visitante, pero puede usar un ID interno vinculado a ese visitante a través de la fusión de sesiones.

| Nombre | Tipo | Descripción                                                                                      |
| ------ | ---- | ------------------------------------------------------------------------------------------------ |
| value  | bool | Parameter for specifying if the `visitorCode` is a unique identifier. Este campo es obligatorio. |

```php theme={null}
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\UniqueIdentifier(true));
```

#### OperatingSystem

`OperatingSystem` contains information about the operating system on the visitor's device.

| Nombre | Tipo  | Descripción                                                                                                            |
| ------ | ----- | ---------------------------------------------------------------------------------------------------------------------- |
| type   | `int` | List of operating systems: `WINDOWS`, `MAC`, `IOS`, `LINUX`, `ANDROID` and `WINDOWS_PHONE`. Este campo es obligatorio. |

<Tip>
  Each visitor can only have one `OperatingSystem`. Adding a second `OperatingSystem` overwrites the first one.
</Tip>

```php theme={null}
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\OperatingSystem(Kameleoon\Data\OperatingSystem::WINDOWS));
```

#### Cookie

`Cookie` contains information about the cookie stored on the visitor's device.

| Nombre  | Tipo    | Descripción                                                                                 |
| ------- | ------- | ------------------------------------------------------------------------------------------- |
| cookies | `array` | Map de objetos string que consta de claves y valores de cookies. Este campo es obligatorio. |

<Tip>
  Each visitor can only have one `Cookie`. Adding a second `Cookie` overwrites the first one.
</Tip>

```php theme={null}
$cookie = new Kameleoon\Data\Cookie([
   "k1" => "v1",
   "k2" => "v2",
]);
$kameleoonClient->addData($visitorCode, $cookie);
```

#### Geolocation

`Geolocation` contains the visitor's geolocation details.

| Nombre                  | Tipo                   | Descripción                                                                                                      |
| ----------------------- | ---------------------- | ---------------------------------------------------------------------------------------------------------------- |
| country (*obligatorio*) | `string`               | The country of the visitor.                                                                                      |
| region (*opcional*)     | <nobr>`?string`</nobr> | The region of the visitor.                                                                                       |
| city (*opcional*)       | <nobr>`?string`</nobr> | The city of the visitor.                                                                                         |
| postalCode (*opcional*) | <nobr>`?string`</nobr> | The postal code of the visitor.                                                                                  |
| latitude (*opcional*)   | `float`                | The latitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees.  |
| longitude (*opcional*)  | `float`                | The longitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |

<Tip>
  * Each visitor can have only one `Geolocation`. Adding a second `Geolocation` overwrites the first one.
</Tip>

```php theme={null}
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Geolocation("France", "Île-de-France", "Paris"));
```

#### ApplicationVersion

`ApplicationVersion` represents the semantic version number of your application.

<Tip>
  A **visitor** can have only one `ApplicationVersion`. Adding a second instance will overwrite the first one.
</Tip>

| Nombre               | Tipo     | Descripción                                                                                                                                      |
| -------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| version (*opcional*) | `string` | The mobile application version. This field must follow semantic versioning. Accepted formats are `major`, `major.minor`, or `major.minor.patch`. |

```php theme={null}
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\ApplicationVersion("10")); // major

$kameleoonClient->addData($visitorCode, new Kameleoon\Data\ApplicationVersion("10.20")); // major.minor

$kameleoonClient->addData($visitorCode, new Kameleoon\Data\ApplicationVersion("10.20.30")); // major.minor.patch
```

### Returned Types

#### DataFile

El `DataFile` contiene los detalles de configuración del SDK.

It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.

| Nombre       | Tipo                         | Descripción                                                                       |
| ------------ | ---------------------------- | --------------------------------------------------------------------------------- |
| featureFlags | `array<string, FeatureFlag>` | A map of [`FeatureFlag`](#featureflag) objects, keyed by feature flag keys.       |
| dateModified | `int`                        | The timestamp (in milliseconds) indicating when the `DataFile` was last modified. |

```php theme={null}
// Retrieves the array of feature flags from the DataFile.
// The array is keyed by feature flag identifiers, with each value being a FeatureFlag object.
$featureFlags = $dataFile->featureFlags;

// Retrieves the last modification timestamp of the DataFile.
// The value is an int representing milliseconds since the Unix epoch.
$dateModified = $dataFile->getDateModified();
```

#### FeatureFlag

`FeatureFlag` representa un conjunto de propiedades que definen un feature flag en sí — por ejemplo, sus [`Variations`](#variation), [`Rules`](#rule), estado del entorno y otros detalles relacionados.

It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.

| Nombre               | Tipo                       | Descripción                                                        |
| -------------------- | -------------------------- | ------------------------------------------------------------------ |
| isEnvironmentEnabled | `bool`                     | Indica si el feature flag está habilitado en el entorno actual.    |
| defaultVariationKey  | `string`                   | The key of the default variation associated with the feature flag. |
| variations           | `array<string, Variation>` | A map of `Variation` objects, keyed by variation keys.             |
| rules                | `array<Rule>`              | A list of `Rule` objects                                           |

```php theme={null}
// Check whether the feature flag is enabled in the current environment
$isEnvironmentEnabled = $featureFlag->isEnvironmentEnabled;

// Retrieve the key of the default variation
$defaultVariationKey = $featureFlag->defaultVariationKey;

// Retrieve the default variation object
$defaultVariation = $featureFlag->getDefaultVariation();

// Retrieve all variations of the feature flag as a map (key = variation key, value = Variation object)
$variations = $featureFlag->variations;

// Retrieve all targeting rules associated with the feature flag
$rules = $featureFlag->rules;
```

#### Rule

`Rule` representa un conjunto de propiedades que definen una regla en sí — por ejemplo, sus [`Variations`](#variation).

It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.

| Nombre     | Tipo                       | Descripción                                            |
| ---------- | -------------------------- | ------------------------------------------------------ |
| variations | `array<string, Variation>` | A map of `Variation` objects, keyed by variation keys. |

```php theme={null}
// Retrieve all variations of the rule as a map (key = variation key, value = Variation object)
$variations = $rule->variations;
```

#### Variation

`Variation` contains information about the assigned variation to the visitor (or the default variation if no specific assignment exists).

| Nombre       | Tipo                      | Descripción                                                                                                                                             |
| ------------ | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name         | `string`                  | The name of the variation.                                                                                                                              |
| key          | `string`                  | The unique key identifying the variation.                                                                                                               |
| id           | `?int`                    | The ID of the assigned variation (or `null` if it's the default variation).                                                                             |
| experimentId | `?int`                    | The ID of the experiment associated with the variation (or `null` if default).                                                                          |
| variables    | `array<string, Variable>` | An array containing the variables of the assigned variation, keyed by variable names. This could be an empty collection if no variables are associated. |

<Note>
  * The `Variation` object provides details about the assigned variation and its associated experiment, while the [`Variable`](#variable) object contains specific details about each variable within a variation.
  * Ensure that your code handles the case where `id` or `experimentId` may be `null`, indicating a default variation.
  * The `variables` array might be empty if no variables are associated with the variation.
</Note>

```php theme={null}
// Retrieving the variation name
$variationName = $variation->name;

// Retrieving the variation key
$variationKey = $variation->key;

// Retrieving the variation id
$variationId = $variation->id;

// Retrieving the experiment id
$experimentId = $variation->experimentId;

// Retrieving the variables map
$variables = $variation->variables;
```

#### Variable

`Variable` contains information about a variable associated with the assigned variation.

| Nombre | Tipo     | Descripción                                                                                                                                  |
| ------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| key    | `string` | The unique key identifying the variable.                                                                                                     |
| type   | `string` | The type of the variable. Possible values: **BOOLEAN**, **NUMBER**, **STRING**, **JSON**, **JS**, **CSS**                                    |
| value  | `?mixed` | The value of the variable, which can be of the following types: **bool**, **int**, **float**, **string**, **stdClass**, **array**, **null**. |

```php theme={null}
// Retrieving the variables map
$variables = $variation->variables;

// Variable type can be retrieved for further processing
$type = $variables["isDiscount"]->type;

// Retrieving the variable value by key
$isDiscount = (bool) $variables["isDiscount"]->value;

// Variable value can be of different types
$title = (string) $variables["title"]->value;
```

### Deprecated methods

<Warning>
  Estos métodos están obsoletos y se eliminarán en la versión `5.0.0` del SDK.
</Warning>

#### getFeatureVariationKey()

* 📨 *Envía datos de seguimiento a Kameleoon*

<Note>
  Use [`getVariation()`](#getvariation) instead.
</Note>

To get feature variation key, call the `getFeatureVariationKey()` method of our SDK.

Este método toma un **visitorCode** and **featureKey** as mandatory arguments to get the variation key for a given user.

If a user has never been associated with this feature flag, the SDK returns a variation key randomly (according to the feature flag rules). If a user with a given **visitorCode** is already registered with this feature flag, it will detect the previous **variation key** value. If the user does not match any of the rules, the default value will be returned, which we can define in your customer's account.

You have to make sure that proper error handling is set up in your code como se muestra en el ejemplo to the right to catch potential exceptions.

Si especifica un `visitorCode`, el método `getFeatureVariationKey()` lo usa como identificador único del visitante, lo cual es útil para la [experimentación entre dispositivos](/developer-docs/cross-device-experimentation). Cuando especifica un `visitorCode` y establece el parámetro `isUniqueIdentifier` en `true`, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.

<Note>
  El parámetro `isUniqueIdentifier` está obsoleto. Utilice en su lugar [`UniqueIdentifier`](#uniqueidentifier).

  `isUniqueIdentifier` también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al `visitorCode` anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
</Note>

```php theme={null}
$visitorCode = $kameleoonClient->getVisitorCode();
$featureKey = "featureKey";
$variationKey = "";

try {
    $variationKey = $kameleoonClient->getFeatureVariationKey($visitorCode, $featureKey);
    switch ($variationKey) {
        case "on":
            // Main variation key is selected for visitorCode
            break;
        case "alternativeVariation":
            // Alternative variation key
            break;
        default:
            // Default variation key
            break;
    }
} catch (Kameleoon\Exception\FeatureNotFound $e) {
    // Feature toggle not yet activated on Kameleoon's side - we consider the feature inactive.
} catch (Kameleoon\Exception\DataFileInvalid $e) {
    // It appears that the configuration has not been loaded
    // and there is no previously saved version of the configuration available.
} catch (Kameleoon\Exception\VisitorCodeInvalid $e) {
    // VisitorCode, which you passed to a method, is invalid and can't be accepted.
} catch (Kameleoon\Exception\FeatureEnvironmentDisabled){
    // The feature flag is disabled for the environment.
} catch (Exception $e) {
    // This is a generic Exception handler which will handle all exceptions.
    echo "Exception: ",  $e->getMessage(), "\n";
}
```

##### Argumentos

| Nombre                        | Tipo   | Descripción                                                                                                                                                                                                                                                                           |
| ----------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorCode                   | string | Identificador único del usuario. Este campo es obligatorio.                                                                                                                                                                                                                           |
| featureKey                    | string | Clave de la funcionalidad que desea exponer a un usuario. Este campo es obligatorio.                                                                                                                                                                                                  |
| timeout                       | ?int   | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the [`default_timeout`](#configuración-adicional) specified in your configuration. |
| isUniqueIdentifier (Obsoleto) | ?bool  | Parámetro opcional para indicar si el visitorCode es un identificador único. If not provided, el valor predeterminado es `null`. The field is optional.                                                                                                                               |

##### Valor de retorno

| Tipo   | Descripción                                                                       |
| ------ | --------------------------------------------------------------------------------- |
| string | Variation key of the feature flag that is registered for a given **visitorCode**. |

##### Excepciones lanzadas

| Tipo                       | Descripción                                                                                                                                                                                                                                                                                                  |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| FeatureNotFound            | Exception indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side). |
| FeatureEnvironmentDisabled | Excepción que indica que el feature flag está deshabilitado para el entorno actual del visitante (por ejemplo, production, staging o development).                                                                                                                                                           |
| VisitorCodeInvalid         | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters).                                                                                                                                                                                                     |
| DataFileInvalid            | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available.                                                                                                                                                                     |

#### getActiveFeatureListForVisitor()

<Note>
  Use [`getActiveFeatures()`](#getActiveFeatures) instead.
</Note>

Este método toma only input parameters: **visitorCode**. Result contains only active feature flags for a given visitor.

```php theme={null}
$visitorCode = "visitor";
$arrayFeatureFlagKeys = $kameleoonClient->getActiveFeatureListForVisitor($visitorCode);
```

##### Argumentos

| Name        | Type   | Description                                                                                                                                                                                                                                                                           |
| ----------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio.                                                                                                                                                                                                                           |
| timeout     | ?int   | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the [`default_timeout`](#configuración-adicional) specified in your configuration. |

##### Valor de retorno

| Type | Description                                                            |
| ---- | ---------------------------------------------------------------------- |
| any  | List of feature flag keys which are active for a given **visitorCode** |

##### Excepciones lanzadas

| Type               | Description                                                                                                                              |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- |
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters).                                 |
| DataFileInvalid    | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available. |

#### getActiveFeatures()

<Note>
  Use [`getVariations()`](#getvariations) instead.
</Note>

`getActiveFeatures` method retrieves information about the active feature flags that are available for the specified visitor code.

```php theme={null}
$visitorCode = "visitor";
$arrayActiveFeatures = $kameleoonClient->getActiveFeatures($visitorCode);
```

##### Argumentos

| Nombre      | Tipo   | Descripción                                                                                                                                                                                                                                                                           |
| ----------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio.                                                                                                                                                                                                                           |
| timeout     | ?int   | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the [`default_timeout`](#configuración-adicional) specified in your configuration. |

##### Valor de retorno

| Tipo  | Descripción                                                                                                 |
| ----- | ----------------------------------------------------------------------------------------------------------- |
| array | An array that contains the assigned variations of the active features using the active feature IDs as keys. |

##### Excepciones lanzadas

| Tipo               | Descripción                                                                                                                              |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- |
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters).                                 |
| DataFileInvalid    | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available. |

#### getFeatureVariable()

* 📨 *Envía datos de seguimiento a Kameleoon*

<Note>
  - Use [`getVariation()`](#getvariation) instead.
  - This method was previously called `obtainFeatureVariable`, which has been deprecated since SDK version `3.0.0` and will be removed in a future release.
</Note>

To get the variable of a variation key associated with a user, call the `getFeatureVariable()` method.

Este método toma un **visitorCode**, **featureKey**, and **variableName** as mandatory arguments to get a variable of the variation key for a given user.

If the user has never been associated with this feature flag, the SDK returns a variable value of the variation key randomly (according to the feature flag rules). If a user with a given **visitorCode** is already registered with this feature flag, the method will detect the **variable** value for the associated **variation**. If the user does not match any of the rules, the default variable will be returned.

Ensure proper error handling is set up in your code como se muestra en el ejemplo to the right to catch potential exceptions.

Si especifica un `visitorCode`, el método `getFeatureVariable()` lo usa como identificador único del visitante, lo cual es útil para la [experimentación entre dispositivos](/developer-docs/cross-device-experimentation). Cuando especifica un `visitorCode` y establece el parámetro `isUniqueIdentifier` en `true`, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.

<Note>
  El parámetro `isUniqueIdentifier` está obsoleto. Utilice en su lugar [`UniqueIdentifier`](#uniqueidentifier).

  `isUniqueIdentifier` es útil en otros escenarios excepcionales, como cuando no puede acceder al `visitorCode` anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
</Note>

```php theme={null}
$visitorCode = $kameleoonClient->getVisitorCode();
$featureKey = "featureKey";
$variableName = "variableName";

try {
    $variationValue = $kameleoonClient->getFeatureVariable($visitorCode, $featureKey, $variableName);
    // Your custom code depending of variableValue
} catch (Kameleoon\Exception\FeatureNotFound $e) {
    // Feature toggle not yet activated on Kameleoon's side - we consider the feature inactive.
} catch (Kameleoon\Exception\FeatureEnvironmentDisabled){
    // The feature flag is disabled for the environment.
} catch (Kameleoon\Exception\VisitorCodeInvalid $e) {
    // VisitorCode, which you passed to a method, is invalid and can't be accepted.
} catch (Kameleoon\Exception\FeatureVariableNotFound $e) {
    // Requested variable not defined on Kameleoon's side.
} catch (Kameleoon\Exception\DataFileInvalid $e) {
    // It appears that the configuration has not been loaded
    // and there is no previously saved version of the configuration available.
} catch (Exception $e) {
    // This is a generic Exception handler which will handle all exceptions.
    echo "Exception: " . $e->getMessage() . "\n";
}
```

##### Argumentos

| Nombre                        | Tipo   | Descripción                                                                                                                                                                                                                                                                           |
| ----------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorCode                   | string | Identificador único del usuario. Este campo es obligatorio.                                                                                                                                                                                                                           |
| featureKey                    | string | Clave de la funcionalidad que desea exponer a un usuario. Este campo es obligatorio.                                                                                                                                                                                                  |
| variableName                  | string | Name of the variable you want to get a value. Este campo es obligatorio.                                                                                                                                                                                                              |
| timeout                       | ?int   | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the [`default_timeout`](#configuración-adicional) specified in your configuration. |
| isUniqueIdentifier (Obsoleto) | ?bool  | Parámetro opcional para indicar si el visitorCode es un identificador único. If not provided, el valor predeterminado es `null`. The field is optional.                                                                                                                               |

##### Valor de retorno

| Tipo | Descripción                                                                                                                                                  |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Any  | Value of variable of variation that is registered for a given **visitorCode** for this feature flag. Possible types: bool, int, float, string, object, array |

##### Excepciones lanzadas

| Tipo                       | Descripción                                                                                                                                                                                                                                                                                                  |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| FeatureNotFound            | Exception indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side). |
| FeatureEnvironmentDisabled | Excepción que indica que el feature flag está deshabilitado para el entorno actual del visitante (por ejemplo, production, staging o development).                                                                                                                                                           |
| VisitorCodeInvalid         | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters).                                                                                                                                                                                                     |
| FeatureVariableNotFound    | Exception indicating that the requested variable has not been found. Check that the variable's ID (or key) matches your code.                                                                                                                                                                                |
| DataFileInvalid            | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available.                                                                                                                                                                     |

#### getFeatureVariationVariables()

<Note>
  * Use [`getVariation()`](#getvariation) instead.
  * This method was previously called `getFeatureAllVariables`, which was removed in SDK version `4.0.0`.
</Note>

To retrieve the all feature variables, call the `getFeatureVariationVariables()` method. A feature variable can be changed easily via our web application.

Este método toma **featureKey** and **variationKey** as mandatory arguments. It will return the data with the object type, as defined on the web interface. The method throws an error (`FeatureNotFound`) if the requested feature flag has not been found in the SDK's client configuration. If the variation key isn't found, the method throws the `FeatureVariationNotFound` error.

```php theme={null}
$featureKey = "test_feature_variables";
$variationKey = "on";

try {
    $variables = $kameleoonClient->getFeatureVariationVariables($featureKey, $variationKey);
    $firstName = $variables["firstName"];
} catch (Kameleoon\Exception\FeatureNotFound $e) {
    // The feature is not yet activated on Kameleoon's side.
} catch (Kameleoon\Exception\FeatureEnvironmentDisabled){
    // The feature flag is disabled for the environment.
} catch (Kameleoon\Exception\FeatureVariationNotFound $e) {
    // The variation is not yet activated on Kameleoon's side, i.e., the associated experiment is not online.
} catch (Kameleoon\Exception\DataFileInvalid $e) {
    // It appears that the configuration has not been loaded
    // and there is no previously saved version of the configuration available.
} catch (Exception $e) {
    // This is a generic Exception handler which will handle all exceptions.
    echo "Exception: " . $e->getMessage() . "\n";
}
```

##### Argumentos

| Nombre       | Tipo   | Descripción                                                                                                                                                                                                                                                                           |
| ------------ | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| featureKey   | string | Key of the feature flag you want to obtain. Este campo es obligatorio.                                                                                                                                                                                                                |
| variationKey | string | Clave de la variación que desea obtener. Este campo es obligatorio.                                                                                                                                                                                                                   |
| timeout      | ?int   | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the [`default_timeout`](#configuración-adicional) specified in your configuration. |

##### Valor de retorno

| Tipo | Descripción                                                                                                                                                   |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Any  | Value of the variation variable that is registered for a given **visitorCode** for this feature flag. Possible types: bool, int, float, string, object, array |

##### Excepciones lanzadas

| Tipo                       | Descripción                                                                                                                                                                                                                                                                                             |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| FeatureNotFound            | Exception indicating that the requested feature ID has not been found in the SDK's internal configuration. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side). |
| FeatureEnvironmentDisabled | Excepción que indica que el feature flag está deshabilitado para el entorno actual del visitante (por ejemplo, production, staging o development).                                                                                                                                                      |
| FeatureVariationNotFound   | Exception indicating that the requested variation ID has not been found in the SDK's internal configuration. Esto suele ser normal y significa que el experimento correspondiente a la variación todavía no se ha activado del lado de Kameleoon.                                                       |
| DataFileInvalid            | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available.                                                                                                                                                                |

#### getFeatureList()

Devuelve una lista de claves de feature flags disponibles actualmente en el SDK.

```php theme={null}
$arrayFeatureKeys = $kameleoonClient->getFeatureList();
```

##### Argumentos

| Nombre               | Tipo   | Descripción                                                                                                                                                                                                                                                   |
| -------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| timeout (*opcional*) | `?int` | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. If a timeout value is not provided, the SDK uses the [`default_timeout`](#configuración-adicional) specified in your configuration. |

##### Valor de retorno

| Tipo            | Descripción               |
| --------------- | ------------------------- |
| `array<string>` | List of feature flag keys |
