PHP code example of supashiphq / php-sdk

1. Go to this page and download the library: Download supashiphq/php-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

supashiphq / php-sdk example snippets




use Supaship\SupashipClient;

$features = [
    'new-ui' => false,
    'theme-config' => [
        'primaryColor' => '#007bff',
        'darkMode' => false,
    ],
];

$client = new SupashipClient([
    'sdkKey' => getenv('SUPASHIP_SDK_KEY'),
    'environment' => 'production',
    'features' => $features,
    'context' => [
        'userId' => '123',
        'email' => '[email protected]',
        'plan' => 'premium',
    ],
]);

$isNewUi = $client->getFeature('new-ui');
$theme = $client->getFeature('theme-config');

$batch = $client->getFeatures(['new-ui', 'theme-config'], [
    'context' => ['userId' => '456'],
]);

$client->getFeature('new-ui', ['context' => ['plan' => 'enterprise']]);



return [
    'sdk_key' => env('SUPASHIP_SDK_KEY'),
    'environment' => env('SUPASHIP_ENVIRONMENT', 'production'),
    /**
     * Central list of flags and fallbacks — keep in sync with what you use in Supaship.
     */
    'features' => [
        'new-ui' => false,
        'theme-config' => [
            'primaryColor' => '#007bff',
            'darkMode' => false,
        ],
    ],
];

use Illuminate\Support\ServiceProvider;
use Supaship\SupashipClient;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(SupashipClient::class, function ($app) {
            $config = $app['config']->get('supaship');

            return new SupashipClient([
                'sdkKey' => $config['sdk_key'],
                'environment' => $config['environment'],
                'features' => $config['features'],
                'context' => [
                    // Filled at boot or request time — see below
                    'appEnv' => config('app.env'),
                ],
            ]);
        });
    }
}

use Illuminate\Support\Facades\Auth;
use Supaship\SupashipClient;

public function boot(): void
{
    $this->app->afterResolving(SupashipClient::class, function (SupashipClient $client) {
        $user = Auth::user();
        if ($user) {
            $client->updateContext([
                'userId' => (string) $user->id,
                'email' => $user->email ?? '',
            ]);
        }
    });
}

use Supaship\SupashipClient;

class DashboardController extends Controller
{
    public function __construct(private readonly SupashipClient $features) {}

    public function index()
    {
        $showNewUi = $this->features->getFeature('new-ui');
        $theme = $this->features->getFeature('theme-config');

        return view('dashboard', compact('showNewUi', 'theme'));
    }
}



namespace App\EventSubscriber;

use Supaship\SupashipClient;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

final class SupashipContextSubscriber implements EventSubscriberInterface
{
    /** @var SupashipClient */
    private $client;

    /** @var Security */
    private $security;

    public function __construct(SupashipClient $client, Security $security)
    {
        $this->client = $client;
        $this->security = $security;
    }

    public function onKernelRequest(RequestEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $user = $this->security->getUser();
        if ($user === null) {
            return;
        }

        $this->client->updateContext([
            // Adjust to your User class / identifier field
            'userId' => method_exists($user, 'getUserIdentifier')
                ? $user->getUserIdentifier()
                : (string) spl_object_id($user),
        ]);
    }

    public static function getSubscribedEvents(): array
    {
        return [KernelEvents::REQUEST => ['onKernelRequest', 8]];
    }
}

use Supaship\SupashipClient;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class HomeController extends AbstractController
{
    #[Route('/', name: 'home')]
    public function index(SupashipClient $features): Response
    {
        $newUi = $features->getFeature('new-ui');

        return $this->render('home.html.twig', ['new_ui' => $newUi]);
    }
}



namespace Config;

class SupashipFeatures
{
    /** @return array<string, mixed> */
    public static function fallbacks(): array
    {
        return [
            'new-ui' => false,
            'theme-config' => [
                'primaryColor' => '#007bff',
                'darkMode' => false,
            ],
        ];
    }
}



namespace Config;

use CodeIgniter\Config\BaseService;
use Supaship\SupashipClient;

class Services extends BaseService
{
    public static function supaship(bool $getShared = true): SupashipClient
    {
        if ($getShared) {
            return static::getSharedInstance('supaship');
        }

        return new SupashipClient([
            'sdkKey' => getenv('supaship.sdkKey') ?: '',
            'environment' => getenv('supaship.environment') ?: 'production',
            'features' => SupashipFeatures::fallbacks(),
            'context' => [
                'ciEnv' => ENVIRONMENT,
            ],
        ]);
    }
}



namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Services;

class SupashipContext implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $client = Services::supaship();
        $session = session();

        if ($session->get('userId')) {
            $client->updateContext([
                'userId' => (string) $session->get('userId'),
            ]);
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
    }
}



namespace App\Controllers;

use CodeIgniter\Controller;
use Config\Services;

class Home extends Controller
{
    public function index()
    {
        $features = Services::supaship();

        $data = [
            'new_ui' => $features->getFeature('new-ui'),
            'theme' => $features->getFeature('theme-config'),
        ];

        return view('home', $data);
    }
}

use Supaship\SupashipClient;
use Supaship\Testing\HttpStub;

$client = new SupashipClient([
    'sdkKey' => 'test-key',
    'environment' => 'test',
    'features' => [
        'new-ui' => false,
        'theme-config' => ['darkMode' => false],
    ],
    'context' => ['userId' => '42'],
    'networkConfig' => [
        'httpHandler' => HttpStub::success([
            'new-ui' => true,
            'theme-config' => ['darkMode' => true, 'primaryColor' => '#111'],
        ]),
    ],
]);

$this->assertTrue($client->getFeature('new-ui'));

'networkConfig' => [
    'httpHandler' => HttpStub::failure(503, 'unavailable'),
],

Route::get('/', function (SupashipClient $client) {
    $isNewUi = $client->getFeature('cool-new-feature', ['context' => [
        'userId' => '123',
    ]]);

    return $isNewUi ? view('new-welcome') : view('welcome');
});



namespace Tests\Feature;

use Supaship\SupashipClient;
use Supaship\Testing\HttpStub;
use Tests\TestCase;

class WelcomeRouteTest extends TestCase
{
    private function clientWithFlag(bool $coolNewFeatureEnabled): SupashipClient
    {
        return new SupashipClient([
            'sdkKey' => 'test',
            'environment' => 'testing',
            'features' => [
                'cool-new-feature' => false,
            ],
            'context' => [],
            'networkConfig' => [
                'httpHandler' => HttpStub::success([
                    'cool-new-feature' => $coolNewFeatureEnabled,
                ]),
            ],
        ]);
    }

    public function test_home_uses_welcome2_when_flag_is_true(): void
    {
        $this->app->instance(SupashipClient::class, $this->clientWithFlag(true));

        $this->get('/')
            ->assertOk()
            ->assertViewIs('new-welcome');
    }

    public function test_home_uses_welcome_when_flag_is_false(): void
    {
        $this->app->instance(SupashipClient::class, $this->clientWithFlag(false));

        $this->get('/')
            ->assertOk()
            ->assertViewIs('welcome');
    }
}

$captured = null;

$client = new SupashipClient([
    'sdkKey' => 'sk',
    'environment' => 'staging',
    'features' => ['promo' => false],
    'context' => ['region' => 'eu'],
    'networkConfig' => [
        'httpHandler' => function (string $url, string $jsonBody) use (&$captured) {
            $captured = json_decode($jsonBody, true, flags: JSON_THROW_ON_ERROR);

            return ['statusCode' => 200, 'body' => '{"features":{"promo":{"variation":true}}}'];
        },
    ],
]);

$client->getFeatures(['promo'], ['context' => ['plan' => 'pro']]);

$this->assertSame('staging', $captured['environment']);
$this->assertSame(['promo'], $captured['features']);
$this->assertSame(['region' => 'eu', 'plan' => 'pro'], $captured['context']);

$client = new SupashipClient([
    'sdkKey' => '...',
    'environment' => 'production',
    'features' => $features,
    'context' => [],
    'networkConfig' => [
        'httpHandler' => static function (string $url, string $jsonBody): array {
            return ['statusCode' => 200, 'body' => '{"features":{}}'];
        },
    ],
]);
bash
composer