AB icon indicating copy to clipboard operation
AB copied to clipboard

A way to set predefined variation

Open jangaraev opened this issue 3 years ago • 1 comments

I need a way to set the variation manually. Here is my original code:

class SplitTestService
{
    const COOKIE_NAME = 'ab_seed';

    protected $container;


    public function __construct()
    {
        $this->container = new Container();

        $this->setSeed();
    }

    public function getHomepageVariation(): string
    {
        return tap(new Test('homepage'), function (Test $test) {
            $this->container->add($test);

            $test->setVariations([
                SplitTests::HOMEPAGE_DEFAULT => 7,
                SplitTests::HOMEPAGE_NEW => 3
            ]);
        })->getVariation();
    }

    private function setSeed(): void
    {
        $seed = request()->cookie(self::COOKIE_NAME);

        if (!$seed) {
            $seed = mt_rand();

            Cookie::queue(self::COOKIE_NAME, (string)$seed);
        }

        $this->container->setSeed($seed);
    }
}

But now in order to ease the development and testing I need to preset the variation from GET variable, something like this:

        return tap(new Test('homepage'), function (Test $test) {
            $this->container->add($test);

            $test->setVariations([
                SplitTests::HOMEPAGE_DEFAULT => 7,
                SplitTests::HOMEPAGE_NEW => 3
            ]);

            // a code to pre-set variation if the specific request variable is passed
            if (!App::environment('production') && ($homepageVariation = request()->query('homepage-variation'))) {
                $test->setVariation('b' === $homepageVariation ? SplitTests::HOMEPAGE_NEW : SplitTests::HOMEPAGE_DEFAULT);
            }
        })->getVariation();

What do you think of it @odino ?

jangaraev avatar Jun 29 '22 06:06 jangaraev

I just want to resolve it a way to stay consistent with a seed set on container level. So that if a user first accesses the page with the query parameter next time the script acts accordingly even without that parameter.

Otherwise I can easily do like as follows:

public function getHomepageVariation(): string
{
    if (!App::environment('production') && ($homepageVariation = request()->query('homepage-variation'))) {
        return 'b' === $homepageVariation ? SplitTests::HOMEPAGE_NEW : SplitTests::HOMEPAGE_DEFAULT;
    }

    return tap(new Test('homepage'), function (Test $test) {
        $this->container->add($test);

        $test->setVariations([
            SplitTests::HOMEPAGE_DEFAULT => 7,
            SplitTests::HOMEPAGE_NEW => 3
        ]);
    })->getVariation();
}

jangaraev avatar Jun 29 '22 06:06 jangaraev