Skip to content

About

PHP SDK for Featurevisor

Resources

Code of conduct

Contributing

Stars

3 stars

Watchers

1 watching

Forks

Repository files navigation

Featurevisor PHP SDK

The Featurevisor PHP SDK evaluates flags, variations and variables in PHP applications, from a datafile it holds in memory.

Table of contents

Install

composer require featurevisor/featurevisor-php:^4.0

The SDK supports PHP 8.0 and later. Upgrading an existing application? Follow the PHP migration guide.

Create an instance

Fetch a datafile and create an instance with it:

<?php

use Featurevisor\Featurevisor;

require 'vendor/autoload.php';

$datafileUrl = "https://cdn.example.com/featurevisor-all.json";

$datafileContent = @file_get_contents($datafileUrl);
if ($datafileContent === false) {
  throw new RuntimeException("Could not load datafile: " . $datafileUrl);
}

// Validate JSON before initialization, keeping the original string for the SDK.
json_decode($datafileContent, false, 512, JSON_THROW_ON_ERROR);

$f = Featurevisor::createFeaturevisor([
  "datafile" => $datafileContent
]);
try {
  echo $f->isEnabled("checkout", ["userId" => "user-4"]) ? "true\n" : "false\n";
} finally {
  $f->close();
}

This example closes the instance at once. In a long running worker, keep it for every evaluation and close it at shutdown. datafile takes a JSON string, or the array json_decode returns with true. Every option is optional, so an instance can start without a datafile and receive one later:

Option Sets
datafile The datafile to evaluate
context The instance context
stickyFeatures, stickyVariables Sticky values
logLevel, onDiagnostic Diagnostics
modules Modules

Create one instance and reuse it, per request or for the life of a worker, as in Octane, RoadRunner or FrankenPHP. On a server that handles many users in one process, give each request a child instance.

Context

Context is a plain array of attribute values. The instance keeps a context of its own, and each evaluation can add to it.

Set it when creating the instance:

$f = Featurevisor::createFeaturevisor([
  "datafile" => $datafileContent,
  "context" => [
    "country" => "nl",
  ],
]);

Add to it later with setContext, or replace it by passing true as the second argument:

$f->setContext([
  "userId" => "user-4",
]);

$f->setContext(
  [
    "userId" => "user-2",
    "country" => "nl",
  ],
  true,
);

Context passed to an evaluation is merged over the instance context for that call only:

$context = [
  "userId" => "user-4",
  "country" => "nl",
];

$f->isEnabled("checkout", $context);

getContext() returns the instance context, and getContext(["country" => "de"]) shows it merged with extra values without storing them.

Dates compare as portable timestamp strings or DateTimeInterface values, by their instant, truncated to milliseconds. Offsets stay within 14 hours and years within 1 and 9999.

Check a flag

isEnabled reads a flag. Dutch users have the new checkout:

$context = [
  "userId" => "user-4",
  "country" => "nl",
];

if ($f->isEnabled("checkout", $context)) {
  // show the new checkout
}

Get a variation

getVariation returns the variation of a feature, or null if the feature is disabled or has none:

$variation = $f->getVariation("pricing", $context);

if ($variation === "treatment") {
  // show the new pricing
}

For user-4 it returns "control", and for user-2 it returns "treatment".

Get a variable

getVariable reads a feature variable with a feature key and a variable key. For user-4, the netherlands rule sets the buy button's label to "Nu kopen":

$label = $f->getVariable("buyButton", "label", $context);

With a context as its second argument, it reads a global variable instead. supportEmail returns "support-nl@example.com" for user-4:

$email = $f->getVariable("supportEmail", $context);

A string second argument means a feature variable, and an array means context for a global variable. The typed methods below follow the same rule.

Arrays are values in PHP, so a returned array is yours to change. Objects inside it may be shared with the datafile, so copy one before changing it, and never change a datafile after passing it to the instance.

Typed methods

Each typed method returns null when the value has a different type, and never converts it. getVariableInteger returns null for the string "1", and getVariableBoolean returns null for "true".

getVariableNumber reads a variable of type number, and also double in datafiles built before v4.

Method Returns
getVariableBoolean bool
getVariableString string
getVariableInteger int
getVariableNumber int or float
getVariableArray A list
getVariableObject An associative array
getVariableJSON Any JSON value
$settings = $f->getVariableObject("checkoutSettings", $context);
// ["currency" => "EUR", "paymentMethods" => ["card"]]

Composed variables

Read a composed global variable like any other global variable. For a string compose alias, choose the getter for the source's type, such as getVariableString for an alias of supportEmail. It returns what the source's own getter returns, including decoded JSON and null, with no wrapper.

A composition is evaluated in this order:

  1. A sticky value for the whole variable, which skips everything after it.
  2. Root conditions. When they miss, no source is read and no override runs. The result is disabledValue when supplied, otherwise null, with reason conditions_unmet.
  3. The sources, with their own sticky values, the context and modules taking part as usual.
  4. The overrides, which run as they do for any global variable.

Compositions have no defaultValue or useDefaultWhenDisabled. With no override match, the reason is variable_composed, and a match reports variable_override_rule, with variableOverridePaths listing every override that changed the value. Cycles, and chains of more than 256 dependencies, fail the whole evaluation.

Default values

Pass defaultVariationValue or defaultVariableValue in the options for when an evaluation produces no value, such as a feature missing from the datafile:

$label = $f->getVariable(
  "buyButton",
  "label",
  $context,
  ["defaultVariableValue" => "Buy"],
);

A default counts as given whenever the key is present, so "", 0, false and null are all valid defaults.

Evaluate everything at once

getFeatureEvaluations evaluates every loaded feature, or only the keys you pass:

$f->getFeatureEvaluations($context, ["checkout", "pricing", "buyButton"]);
// [
//   "checkout" => ["enabled" => true],
//   "pricing" => ["enabled" => true, "variation" => "control"],
//   "buyButton" => [
//     "enabled" => true,
//     "variation" => "treatment",
//     "variables" => ["label" => "Nu kopen", "colour" => "#2563eb"],
//   ],
// ]

getVariableEvaluations does the same for global variables:

$f->getVariableEvaluations($context, ["supportEmail", "checkoutSettings"]);

To see what is loaded without evaluating anything:

  • getFeatureKeys() lists every feature in the datafile, enabled or not.
  • getVariableKeys() lists global variables, and getVariableKeys("buyButton") lists that feature's variables.
  • hasVariations("pricing") is true when a feature has variations, and false for an unknown feature.

Hand results from server to client

Both results have the shape sticky values take. A server can evaluate once per request and pass the results to the browser, so the first render matches what the server saw. The JavaScript SDK's sticky values read them there.

Sticky values

Sticky values take precedence over the datafile. Use them to keep a user's result fixed, to answer before a datafile has loaded, or in unit tests:

$f = Featurevisor::createFeaturevisor([
  "stickyFeatures" => [
    "checkout" => ["enabled" => true],
    "pricing" => [
      "enabled" => true,
      "variation" => "treatment",
    ],
  ],
  "stickyVariables" => [
    "supportEmail" => "support@example.com",
  ],
]);

A sticky feature can also set variables. Change sticky values later with setStickyFeatures and setStickyVariables. Both merge by default, and replace the whole map when the second argument is true:

$f->setStickyFeatures(
  [
    "checkout" => ["enabled" => false],
  ],
  true,
);

Update the datafile

setDatafile gives the instance a newer datafile, as a JSON string or a decoded array:

$f->setDatafile($datafileContent);

It returns true when the datafile is accepted, even if nothing changed, and false when it is rejected or the instance is closed. A rejected datafile leaves the previous one in place and is reported through diagnostics.

Merge or replace

By default, the new datafile is merged into the current one:

  • Its features, segments and global variables replace those with the same keys.
  • Definitions it does not contain are kept.
  • Its revision and schemaVersion are taken.

Pass true to replace the current datafile entirely. Do this when refreshing a complete datafile, so definitions removed from it do not linger:

$f->setDatafile($datafileContent, true);

Merging is what lets one instance hold datafiles for several targets, loaded as each part of the application needs them. See Loading datafiles on demand.

Refresh on an interval

A request that builds its own instance reads the datafile each time, so cache it, such as in APCu for a few minutes. A long running worker refreshes in place, from its event loop or a timer:

function refreshDatafile(Featurevisor $f, string $datafileUrl): void
{
  $datafileContent = @file_get_contents($datafileUrl);
  if ($datafileContent !== false) {
    $f->setDatafile($datafileContent, true);
  }
}

A failed fetch keeps the previous datafile. setDatafile does not throw for an invalid datafile, it reports it through diagnostics. Each accepted update emits datafile_set.

Child instances

A worker that handles many users gives each request a child with its own context:

$child = $f->spawn([
  "userId" => "user-4",
  "country" => "nl",
]);

$child->isEnabled("checkout");
  • The child copies the parent's context keys when it is spawned, and its own values win. Keys the parent adds later still reach it.
  • Sticky values are not inherited. Pass ["stickyFeatures" => ...] as the second argument when the child needs some.
  • A child has the parent's evaluation methods, plus getContext, setContext, setStickyFeatures, setStickyVariables, on and close.
  • close() removes the child's listeners, including the ones it registered on its parent.

Events

on subscribes to an event and returns a function that unsubscribes.

datafile_set

Emitted for every accepted datafile:

$unsubscribe = $f->on("datafile_set", function (array $event) {
  $revision = $event["revision"];
  $previousRevision = $event["previousRevision"];
  $revisionChanged = $event["revisionChanged"];
  $replaced = $event["replaced"];
  $features = $event["features"];
  $variables = $event["variables"];
  $segments = $event["segments"];

  // evaluate the listed features and variables again
});

$unsubscribe();

replaced says whether the datafile replaced the previous one or merged into it. features and variables list the keys whose results may have changed: those added, updated or removed, and those that depend on them through conditions, segments and composition sources, however indirectly. Evaluate those again and you have everything that changed.

segments lists the segments whose definitions were added, changed or, on a replace, removed. If a new datafile has the netherlands segment take Belgium too, segments is ["netherlands"], and features and variables include checkout and supportEmail, whose conditions read it. The first datafile lists every feature, global variable and segment. sections lists the changed entries of each datafile section, such as schemas.

context_set

Emitted by setContext:

$f->on("context_set", function (array $event) {
  $context = $event["context"]; // the new instance context
  $keys = $event["keys"]; // the top level keys whose values changed
});

keys compares values, so a key set again to the value it already holds is not listed. Starting from the instance context ["userId" => "user-4", "country" => "nl"]:

$f->setContext([
  "country" => "de",
]);
// keys: ["country"]

$f->setContext([
  "country" => "de",
  "plan" => "paid",
]);
// keys: ["plan"]

$f->setContext([
  "userId" => "user-4",
  "country" => "de",
], true);
// keys: ["plan"]

A replace also lists the keys it removed, as plan above. Arrays compare item by item, lists in order and other arrays by key, and numbers by value, so 30 and 30.0 are the same while true and 1 are not. An object given again as the same instance counts as changed, since it may have been changed in place.

sticky_features_set

Emitted by setStickyFeatures, with features, every feature that had a sticky value before the call or has one after it, and replaced:

$f->on("sticky_features_set", function (array $event) {
  $features = $event["features"];
});

sticky_variables_set

Emitted by setStickyVariables, with variables and replaced:

$f->on("sticky_variables_set", function (array $event) {
  $variables = $event["variables"];
});

error

Emitted for every diagnostic at error:

$f->on("error", function (array $event) {
  error_log($event["diagnostic"]["message"]);
});

Diagnostics

The SDK reports what happens during evaluation as diagnostics, at one of five levels: fatal, error, warn, info and debug. By default, those at info and above go to the console with a [Featurevisor] prefix.

debug shows how each value was evaluated, which helps when a result surprises you. Set the level when creating the instance, or later:

$f = Featurevisor::createFeaturevisor([
  "logLevel" => "debug",
]);

$f->setLogLevel("warn");

To send diagnostics somewhere other than the console, pass a handler:

$f = Featurevisor::createFeaturevisor([
  "onDiagnostic" => function (array $diagnostic) {
    // send $diagnostic["level"], ["code"], ["message"] and ["details"] to your observability system
  },
]);

Every diagnostic has level, code, message and a details array. Values about an evaluation, such as featureKey, variableKey, reason and evaluation, are in details. module, moduleName and originalError say where an error came from, when known. A handler that throws stops neither other handlers nor evaluations.

Evaluation errors

conditions_parse_error is an error diagnostic for malformed stringified conditions. It fires once per selector per datafile load, on first read for v4 datafiles and during setDatafile for v3 datafiles. Its details contain conditions with the raw string, entityType and entityKey.

The whole malformed selector evaluates to false, even under not, while other entities keep working and setDatafile returns true for an otherwise valid datafile. A malformed root gate is unmet and reports conditions_unmet.

Dependency cycles fail the whole evaluation with reason error. SDK evaluation errors return the ordinary false or null result, and other entities keep working.

Evaluation details

The evaluate methods return how a value was reached, not only the value:

$f->evaluateFlag("checkout", $context);
$f->evaluateVariation("pricing", $context);
$f->evaluateVariable("buyButton", "label", $context);
$f->evaluateVariable("supportEmail", $context);

For user-4, evaluateFlag returns:

[
  "type" => "flag",
  "featureKey" => "checkout",
  "reason" => "rule",
  "bucketKey" => "user-4.checkout",
  "bucketValue" => 89312,
  "ruleKey" => "netherlands",
  "enabled" => true,
]

Every evaluation has a type and a reason. Others appear when they apply:

  • featureKey, absent for global variables, so check for it before using it
  • bucketKey and bucketValue, from 0 to 100,000, and the ruleKey that matched
  • enabled, variation and variationValue
  • variableKey, variableValue, variableSchema and variable, the global variable's definition
  • variableOverrideKey and variableOverrideIndex when a keyed override matched, and variableOverridePath for a nested one
  • variableOverridePaths, every override path matched in order, for accumulating overrides. The singular fields describe the last match
  • conditions when a root gate stopped the evaluation
  • error when evaluation failed

Evaluation reasons

Test specs can assert them.

Reason Meaning
feature_not_found The feature is not in the datafile
disabled The feature is disabled
no_variations A variation was requested from a feature without variations
variation_disabled A disabled feature returned its disabledVariationValue
variable_not_found The feature variable or global variable is not in the datafile
variable_default The variable returned its default value
variable_composed A global variable read its composition sources with no override match
variable_disabled A disabled feature returned the variable's disabled value
variable_override_variation A feature variable override matched inside a variation
variable_override_rule A feature variable override or global variable override matched
conditions_unmet Root conditions did not match. See conditions
no_match No rule, allocation or variation matched, or the bucket fell outside the rollout
forced A force entry supplied the result
sticky A sticky value supplied the result
rule A matching rule supplied the result
allocated Bucketing allocated the result
error Evaluation failed. See error

Modules

A module hooks into evaluation. It can change the context before an evaluation, change the result after it, or decide how users are bucketed. Every part is optional:

$auditModule = [
  "name" => "audit",

  "setup" => function (array $api) {
    $api["onDiagnostic"](function (array $diagnostic) {
      // diagnostics at this module's own level
    });
    $api["reportDiagnostic"]([
      "level" => "info",
      "code" => "module_ready",
      "message" => "Ready for revision " . $api["getRevision"](),
    ]);
  },

  "beforeEvaluation" => function (array $options): array {
    // type, featureKey, variableKey and context
    $options["context"]["plan"] = "paid";
    return $options;
  },

  "afterEvaluation" => function (array $evaluation, array $options): array {
    // log $evaluation["error"] when the reason is error
    return $evaluation;
  },

  "bucketKey" => fn (array $options): string => $options["bucketKey"],

  // between 0 and 100,000
  "bucketValue" => fn (array $options): int => $options["bucketValue"],

  "close" => function () {
    // clean up when the instance closes
  },
];

beforeEvaluation and afterEvaluation run for flags, variations and both kinds of variable, every module in registration order, and must return the options and the evaluation, changed or not. A variable evaluation without a featureKey is a global one.

beforeEvaluation also runs when a schema validates, with type schema and the schema's key instead of a featureKey, so context it adds reaches the schema's conditions too. afterEvaluation does not run then, since a validation's result is not an evaluation. Check type before reading the keys.

The before evaluation and after evaluation phases each use the module membership at the start of that phase, and the bucket key and bucket value phases each use their own. Adding or removing a module during a phase does not change the iteration already in progress.

If setup throws, the module is not registered. The SDK removes the diagnostic subscriptions it made, reports module_setup_error, and calls its close if it has one.

Dependency evaluations

Conditions and composition members are evaluated through modules too. Their options include dependencyOf, naming the requesting evaluation by type, featureKey and variableKey. dependencyPurpose is "condition" for an eligibility check and "composition" for a consumed member value. Direct calls have neither.

When tracking consumed evaluations, skip eligibility checks, not every read with dependencyOf, since a variation read through a composition can be an experiment exposure. Within one call, repeated reads with the same inputs and purpose are memoized, so callbacks can run fewer times than there are reads. Return the same result for the same input during one evaluation, and pass values that change through the context.

Register a module

Pass modules when creating the instance, or add them later:

$f = Featurevisor::createFeaturevisor([
  "modules" => [$auditModule],
]);

$remove = $f->addModule($trackingModule);

// later
$remove();
$f->removeModule("audit");

Read the datafile from a module

A package, such as schemas, reads the datafile through the API setup receives:

  • $api["getEntry"]($section, $key) returns an entry of a section, a top level key besides Featurevisor's own whose value is an object, such as schemas. $api["getEntryKeys"]($section) lists a section's keys.
  • $api["matchConditions"]($conditions, $context, $options) answers the package's own conditions with the instance's engine, segments and feature leaves included. Its readers answer leaves only the package knows, such as input.
  • $api["evaluate"](["type" => ..., "key" => ..., "context" => ...], $callback) evaluates the package's own entry as a getter evaluates a flag. Every module's beforeEvaluation runs first, with type and key naming the entry, and the conditions the callback answers with $scope->matchConditions($conditions, $readers) read the context the modules leave, in one dependency session. The callback's result is returned.

Feature and variable leaves reach modules as dependencies, with dependencyOf naming the package's entry. A module with no evaluation callbacks, such as a package's, costs evaluations nothing.

Schemas

Schemas validate data against the schemas your datafiles deliver, with the instance you already have, and the same rules, messages and conditions as @featurevisor/schemas in JavaScript.

Schemas are experimental, so their API may change in a minor release, as in JavaScript.

Create a schemas instance

They ship in this package, under Featurevisor\Schemas, so there is nothing else to install. Create it from the SDK instance. Call it $s, as the SDK instance is $f:

use Featurevisor\Schemas\Schemas;

$s = Schemas::create($f);

It holds no copy of the schemas. Every call reads the datafile $f has now, so a new datafile applies at the next validation. Compiled schemas are kept until a datafile changes them, so a worker can keep one for its life.

Validate a value

$value = [
  "email" => "user-1@example.com",
  "displayName" => "A",
  "country" => "nl",
];

$result = $s->validate("signUp", $value);

if (!$result->isValid()) {
  // show $result->issues beside the form's fields
}
  • $s->validate($key, $value) returns a ValidationResult with the value itself and its issues. It never coerces, fills defaults or strips keys.
  • $s->isValid($key, $value) returns a boolean.
  • $s->parse($key, $value) returns the value, or throws Featurevisor\Schemas\ValidationException, for a controller or a script that wants a value or a stop.
  • All three take a context as a third argument, merged over the instance's, for the conditions a schema's rules read.
  • A validation runs as the schema's own evaluation, so a module's beforeEvaluation sees it, with type schema and the schema's key, and context the module adds reaches every condition, as it does for flags.
  • $s->keys() lists the schemas the datafile has, and $s->has($key) says whether it has one.

A value can be arrays, objects with public properties, JsonSerializable objects and backed enums, read as json_encode writes them. A list is an array, and any other PHP array an object. An empty array is an empty object where a schema wants one, since PHP decodes {} as [] with arrays. const and enum compare an empty array as an empty list, so pass new \stdClass() for an empty object they list.

A key the datafile does not have fails closed, with one schemaNotFound issue, and a schema_not_found diagnostic at warn, once per key and datafile revision. A field that a schema in the datafile lacks reports only its schemaNotFound issue. The instance keeps no handle for a key the datafile lacks.

Read the issues

Every issue has a message, a path of object keys and list indices, the code of the rule that failed, its params, and the schema validated. $issue->field() gives its path as a form names a field, such as items.0.name.

Validation reports every issue it finds, so a form can mark every field at once. An issue about a field with a title carries it in params["title"], and one whose rule a mutation set names it in mutation.

Code Raised when
type The value has another type
const, enum The value is not one allowed
minimum, maximum A number is out of range
minLength, maxLength A string is too short or too long
pattern, format A string has the wrong shape
minItems, maxItems A list has too few or too many items
uniqueItems A list repeats an item
required, additionalProperties A key is missing, or there is one it does not allow
oneOf No branch matches, or more than one does
refine An issues entry matches, or a check in code fails
refineError A check in code throws, or the schema itself cannot be applied
schemaNotFound The datafile has no such schema or field

$result->flatten() groups the messages by field, in the shape of Zod's flattenError, and serializes to JSON as formErrors and fieldErrors. flatten() on a ValidationException does the same, for an error response.

Get a handle

A handle is one schema as an object your code holds: it validates, and describes the schema's fields, constraints, choices and annotations for a form. $s->get($key) gives one:

$signUp = $s->get("signUp");

A handle is stable, and reads the current datafile whenever it is used, so keep one for the life of a worker.

Member What it is
validate, isValid, parse As on $s, without the key
field($path) The handle of one field, such as field("displayName")
fields() An object's fields' handles, in order, each with its name()
constraints(), fieldConstraints() HTML validation attributes, fieldConstraints() by field path on an object, below
options(), fieldOptions(), option($value) Its choices, fieldOptions() by field path on an object, and one choice by value
renderAs() What its rules say the field renders as, such as "select"
annotations() Its annotations
withInput($input) The same handle with an input
reads() The fields its rules' conditions read
subscribe($listener) A call when a new datafile changes the schema
key(), path(), name() The schema's key, and the field's path and own name

required holds for every key it lists, whether or not properties names it, so an object with only additionalProperties, or with no properties at all, still reports each missing key.

field takes a field name as form libraries write it: address.city, items.0.name or items[0].name, and items[].name for every item alike. It follows references and stops at oneOf. A path the schema lacks fails closed with schemaNotFound. PHP has no "no value" for a field handle, since null is a JSON value, so a field handle validates the value it is given.

Read constraints and choices

constraints() are named after HTML attributes:

$constraints = $signUp->field("displayName")->constraints();
$constraints->required;  // true
$constraints->minLength; // 2
$constraints->maxLength; // 40

$constraints->attributes();
// ["required" => true, "minlength" => 2, "maxlength" => 40], for a template
  • required, when the key is required, so an input left empty fails
  • minLength and maxLength, from the same rules on a string
  • min and max, from minimum and maximum on a number
  • step of 1, for an integer
  • multiple, for a list, such as a multiple select

options() lists a field's choices in the order of its rules, each with what its annotations say, and option($value) finds one, for showing a value saved earlier:

$country = $signUp->field("country");

$country->options();             // nl, de and be, each a SchemaOption
$country->option("nl")->title;   // "Netherlands"
$country->option("fr");          // null

A schema the datafile lacks has no constraints and no choices, so a form renders before its datafile arrives. renderAs() answers the switch every generic form writes, from the field's rules alone: "text", "date-time", "version", "number", "boolean", "select", "multiselect", "object" or "list". Your own annotation, such as input: select, still wins over it.

Read annotations

A handle's annotations() are its node's own, and fields() gives an object's fields in its order:

$signUp->annotations()["title"]; // "Create your account"

array_map(fn ($field) => $field->path(), $signUp->fields());
// ["displayName", "email", "country"]

default is the value a form starts a field with, and a handle from withInput has the one a mutation sets. Fields an order annotation leaves out come after it, in name order by Unicode code point, as in every SDK. A field or schema the datafile lacks has no annotations. Annotations on Schemas writes them.

Follow the values typed so far

A handle's constraints and choices describe the schema's own rules, which no condition changes. withInput($input) gives the same handle with an input, such as a form's values, with the mutations that match it applied, so a tax ID shows as required once a business account is chosen:

$values = [
  "accountType" => "business",
  "country" => "nl",
];

$signUp->field("taxId")->constraints()->required;                     // false
$signUp->withInput($values)->field("taxId")->constraints()->required; // true

Every member follows the input, at every depth. reads() lists the fields the conditions of a handle's mutations and issues read, so a form can validate again only when one of them changes.

Choose the messages

messages on Schemas::create words every schema's issues, per code, as a template or a function of the params:

$s = Schemas::create($f, messages: [
  "required" => "This field is required",
  "maxLength" => fn (array $params) => "{$params['length']} of {$params['maxLength']} characters",
]);

messages on $s->get words one form, by field and code, such as ["displayName" => ["maxLength" => "Names fit {maxLength} characters"]]. For each issue, the first of these that words it wins:

  1. A check in code's own message, then the form's.
  2. The schema's own, and then the message of its issues entry.
  3. The application's, from messages on Schemas::create.
  4. The default, in English.

translate on Schemas::create gets each issue, with the message chosen, and returns what the issue says, or null to keep it. With translations, messages holds keys, such as errors.required, and translate turns each into text:

$s = Schemas::create($f, translate: fn ($issue, $info) => __($issue->message, $issue->params));

Check in code

Some checks need your application, such as whether a display name is taken. Give them to a handle in refine, each a Refinement with a key and a check, and the path it checks, a message and reads as it needs them:

use Featurevisor\Schemas\Refinement;

$signUp = $s->get("signUp", refine: [
  new Refinement(
    key: "nameAvailable",
    path: "displayName",
    check: fn ($displayName, $info) => !User::where("display_name", $displayName)->exists(),
    message: "That display name is taken",
  ),
]);

$result = $signUp->validate($value);
  • check gets the value at its path, and a CheckInfo with the whole input and the context, where $info->read("country") reads another field. It returns true when the value passes.
  • In a field's handle, check gets the field's value as its input, where a handle from a view at the root gets the whole input with the field's value in its place.
  • A check that throws fails the value closed with refineError, and reports one schema_check_error diagnostic at error for that schema and check, once per datafile revision.
  • It runs after the schema's rules, and only when nothing at or inside its path has an issue already, so a name that is too short never reaches your database.
  • Without a path, the check gets the whole value, and runs only when the value has no issue at all. reads names other fields whose issues hold it back too, such as items for a check of an order's total.
  • Its issue has code refine and params["refine"] "nameAvailable", with the field's title. A check that throws gives refineError, and validation fails closed.
  • Checks run in order, synchronously.

Options from your application

Some lists only your application can answer for, such as cities for a city field. Give a handle an OptionSource in optionSources, with a key, a path, and a search, a lookup or both:

use Featurevisor\Schemas\OptionSource;

$cities = new OptionSource(
  key: "cities",
  path: "city",
  search: fn ($query, $info) => City::where("country", $info->read("country"))->search($query)->pluck("name")->all(),
  lookup: fn ($city, $info) => City::where("country", $info->read("country"))->firstWhere("name", $city)?->only("title"),
  reads: ["country"],
  message: "Choose a city from the list",
);

$signUp = $s->get("signUp", optionSources: [$cities]);
$city = $signUp->withInput(["country" => "nl"])->field("city");

$city->search("am");
// Amsterdam and Amersfoort
  • search returns choices shaped like options(), or values alone. A handle's search passes it the values given to withInput, so the cities follow the country. isSearchable() says whether a field has one.
  • lookup returns the choice for a value, true when it carries nothing more, or null when there is none. A handle's lookup($value) returns the schema's own choice first, then the source's.
  • Validation runs lookup as a check in code, after the schema's rules, only for a value that is there, and not while a field reads names has an issue. A value it cannot find has code enum, worded by message.

Validate on the server

parse answers a request with a value or a ValidationException, whose flatten() gives the issues by field:

use Featurevisor\Schemas\ValidationException;

Route::post("/sign-up", function (Request $request) use ($s) {
  try {
    $value = $s->parse("signUp", $request->all());
  } catch (ValidationException $error) {
    return response()->json($error->flatten(), 422);
  }

  return createAccount($value);
});

A rule changed in your project reaches the browser and the server at their next datafile, so the two never disagree.

Listen for changes

subscribe calls back when a new datafile changes the schema, through a schema it references too, and returns a function that stops it:

$stop = $s->get("signUp")->field("country")->subscribe(fn () => renderChoices());

A datafile whose schema is unchanged calls nothing. $s->close() stops every listener the instance started and removes its module from the Featurevisor instance.

Patterns

Schema patterns are JavaScript regular expressions with the u flag, and they mean the same here: ^ and $ are the start and end of the value, \s is JavaScript's whitespace, and . reads an emoji as one character, as lengths do. A pattern that does not compile with u, such as [a-z\_], fails every value with one schema_pattern_unsupported diagnostic. A mutation whose operations cannot be applied fails the value with refineError and one schema_mutation_error diagnostic. Validation follows at most 128 references inside one another, which limits how deep a value can nest through them, so a tree whose nodes each reference the tree's schema can be 128 levels deep. The node at the 129th fails closed with refineError and one schema_reference_depth diagnostic, whose message says the value is nested more than 128 references deep. A type the package does not know fails every value with a type issue. These error diagnostics, and schema_not_found, are reported once per datafile revision.

Close

close() removes event listeners and closes modules, on the instance and on a child:

$f->close();

OpenFeature

The provider is compatible with OpenFeature PHP SDK 2.x, tested with 2.0.0 and 2.3.0. OpenFeature remains optional and is not installed or loaded by the base Featurevisor SDK.

Installation

composer require featurevisor/featurevisor-php:^4.0 open-feature/sdk:^2.3

Provider setup

use Featurevisor\OpenFeatureProvider;
use OpenFeature\OpenFeatureAPI;
use OpenFeature\implementation\flags\Attributes;
use OpenFeature\implementation\flags\EvaluationContext;

$provider = new OpenFeatureProvider([
    'datafile' => $datafileContent,
]);

$api = OpenFeatureAPI::getInstance();
$api->setProvider($provider);

$client = $api->getClient();
$enabled = $client->getBooleanValue(
    'checkout',
    false,
    new EvaluationContext('user-4', new Attributes(['country' => 'nl']))
);

$f->setStickyVariables(['supportEmail' => 'new@example.com']);

The current OpenFeature PHP SDK does not expose provider shutdown through its API. Call $provider->shutdown() when your application shuts down. This closes a Featurevisor instance created by the provider and releases provider subscriptions.

Flag key mapping

OpenFeature key Featurevisor evaluation
checkout Boolean flag for checkout
checkout:variation Variation value for checkout
buyButton:label Variable label for buyButton
variable:supportEmail Global variable supportEmail

Boolean variables use the boolean resolver. Integer and double variables use their matching numeric resolvers. Arrays, objects, and JSON variables use the object resolver.

The first separator divides the feature key from the selector. Use keySeparator and variationKey when project keys require a different grammar:

$provider = new OpenFeatureProvider(
    options: ['datafile' => $datafileContent],
    keySeparator: '/',
    variationKey: '$variation'
);

This makes checkout/$variation the variation key and buyButton/label a variable key.

Global variables use the variable prefix by default. Configure globalVariablePrefix when that word is already meaningful in your project:

$provider = new OpenFeatureProvider(
    options: ['datafile' => $datafileContent],
    globalVariablePrefix: 'global'
);

This maps global:supportEmail to the global variable supportEmail.

Context mapping

OpenFeature's targeting key maps to userId by default. Use targetingKeyField to map it to another Featurevisor context field:

$provider = new OpenFeatureProvider(
    options: ['datafile' => $datafileContent],
    targetingKeyField: 'accountId'
);

OpenFeature context attributes are copied without mutating the incoming context. Nested arrays are preserved. Dates are normalized to UTC ISO strings with millisecond precision, matching the JavaScript provider.

The provider distinguishes an absent targeting key from an explicitly empty one when called directly. The upstream OpenFeature PHP client merges contexts using only nonempty targeting keys, so it drops an empty key before the provider receives it. To override an existing targeting field with an empty string through that client, set the configured field itself as an attribute, such as ['userId' => '']. Clear any inherited nonempty targeting key at its source first, since it would overwrite that attribute again. A narrower empty key may not clear it.

Resolution details

The provider maps Featurevisor evaluation results to OpenFeature details:

Featurevisor result OpenFeature result
Composed variable, forced, sticky or rule match TARGETING_MATCH
Traffic allocation SPLIT
Unmet root conditions, disabled variation or disabled variable DISABLED
No match or variable default DEFAULT
Missing feature, variable, or variations ERROR with FLAG_NOT_FOUND
Wrong resolver type ERROR with TYPE_MISMATCH
Invalid datafile ERROR with PARSE_ERROR
Evaluation failure ERROR with GENERAL

Errors return the default value supplied to OpenFeature. A malformed datafile uses the stable message Could not parse datafile. A later successful setDatafile() call clears the parse error.

Selected Featurevisor variations are exposed as the OpenFeature variant when available. OpenFeature PHP SDK 2.x does not expose flag metadata in resolution details, so Featurevisor metadata such as revision, rule key, and bucket value cannot currently be returned by this provider.

Tracking

Tracking is a no-op unless onTrack is configured:

$provider = new OpenFeatureProvider(
    options: ['datafile' => $datafileContent],
    onTrack: function ($name, $context, $details) {
        echo $name;
    }
);

Using an existing Featurevisor instance

Reuse an existing Featurevisor instance:

$featurevisor = Featurevisor::createFeaturevisor(['datafile' => $datafileContent]);
$provider = new OpenFeatureProvider(featurevisor: $featurevisor);

The caller owns an instance passed this way. Calling $provider->shutdown() does not close it. Call $featurevisor->close() when every consumer is finished with it. When the provider creates the instance from options, the provider owns and closes it. If both are supplied, $featurevisor takes precedence over $options. Shutdown is safe to call more than once.

An invalid initial datafile returns PARSE_ERROR during evaluation, independently of logLevel. The upstream PHP provider interface has no registration lifecycle to fail. A valid datafile update clears the error. Shutdown removes provider subscriptions and closes only an owned instance.

See the OpenFeature provider guide for resolution reasons, errors, lifecycle, and providers for other languages.

CLI usage

Install the package with Composer:

composer require featurevisor/featurevisor-php:^4.0

Run the commands below from the directory containing vendor.

The native test runner requires Node.js 24 or later. Install the Node.js CLI in your Featurevisor project:

npm install --save-dev @featurevisor/cli@^4.0.0

Project parsing and datafile generation use npx featurevisor. Evaluations run through this PHP SDK. The SDK runtime has no Node.js dependency. All three commands accept repeated --target=<target> options.

Use the Node.js CLI directly for authoring commands such as init, lint, build and list. Native commands delegate project parsing, test expansion and datafile generation to Node.js, then evaluate the results with this SDK.

Options use kebab case, such as --project-directory-path. The camelCase forms from earlier releases still work, and --root-directory-path is an alias for --project-directory-path. Pass values as --name=value or --name value. Repeat --target to select several targets in order. Run <command> --help to list every option.

--n and -n accept both value forms. Repeat --populate-uuid for multiple context attributes. Quote JSON and paths containing spaces.

Test

vendor/bin/featurevisor test \
  --project-directory-path=/path/to/featurevisor-project \
  --only-failures

See Testing for authoring specs and Checks for check syntax and operators.

Useful test options:

  • --key-pattern=<pattern> and --assertion-pattern=<pattern> filter tests.
  • --entity-type=scenario selects scenarios, and --entity-type=schema schema specs, which validate their values with Featurevisor\Schemas as the JavaScript CLI does. --set=<set> selects one project set. Omitting --set runs all sets.
  • --case=<id> reruns one expanded case. Copy the opaque ID or rerun command from a failure report.
  • --json --pretty produces an indented JSON report.
  • --coverage reports observed rule and override selections. --uncovered lists features and global variables without associated specs.
  • --only-failures, --quiet, --verbose and --show-datafile control diagnostic output.

Bootstrap, argument and project discovery failures may produce no JSON report. Check the exit status and standard error as well as any report. Reruns retain the PHP executable and CLI script. Without a project path, rerun from the same project directory.

Printed rerun commands use POSIX shell quoting. JSON reports also include raw argument arrays.

Benchmark

The examples below use a project without environments. Add --environment=<name> if your project configures environments. In a sets project, omit --set to run every set or pass --set=<name>. Repeat --target=<key> to evaluate specific target datafiles. The Node.js CLI validates these options and builds the datafiles. PHP evaluates them. Replace checkout with a feature defined in your project.

vendor/bin/featurevisor benchmark \
  --project-directory-path=/path/to/featurevisor-project \
  --feature=checkout \
  --context='{"country":"nl"}' \
  --n=1000

Use --variation for a variation or --variable=<key> for a feature variable. Omit --feature to benchmark a global variable. Do not combine --variation with --variable. See Benchmarking.

Assess distribution

vendor/bin/featurevisor assess-distribution \
  --project-directory-path=/path/to/featurevisor-project \
  --feature=checkout \
  --populate-uuid=userId \
  --n=1000

The PHP CLI also accepts --variation or --variable=<key> to assess a variation or feature variable instead of the enabled state. These selectors are specific to this runner and are not supported by the Node.js assess-distribution command. Repeat --populate-uuid=<key> to generate UUID values for multiple context attributes. See Assess distribution.

GitHub repositories

The aggregate evaluation reference has moved to Evaluate everything at once.

The sticky state reference has moved to Sticky values.

Development of this package

Setting up

Clone the repository, and install the dependencies using Composer:

$ composer install

Running tests

$ composer test

The native tests cover runtime conformance and project integration.

Run vendor/bin/phpunit tests/ReadmeInitializationTest.php to execute the actual initialization snippet against a local HTTP fixture. This check also runs in the ordinary SDK suite and CI.

Run the complete local release check with:

$ make check

The OpenFeature and base SDK tests can also be run separately with make test-openfeature and make test-base.

To run the SDK against Featurevisor example-1 from the local monorepo checkout:

$ make test-example-1

Releasing

The next release is 4.1.0. Composer derives the package version from the Git tag, so composer.json deliberately has no version field. The Packagist workflow accepts v4 semantic version tags. Run composer validate --strict, composer sast, make test-base and make test-openfeature before tagging. OpenFeature remains optional for base consumers. Provider consumers also install open-feature/sdk:^2.3.

  • Manually create a new release on GitHub
  • Tag it with a prefix of v, like vX.Y.Z
  • The Packagist workflow notifies Packagist after the tag is pushed

License

MIT © Fahad Heylaal

About

PHP SDK for Featurevisor

Resources

Code of conduct

Contributing

Stars

3 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages