Skip to content

Instantly share code, notes, and snippets.

@Zayon
Last active June 6, 2019 15:07
Show Gist options
  • Save Zayon/ac13520016131b78e06d9c3872ea605b to your computer and use it in GitHub Desktop.
Save Zayon/ac13520016131b78e06d9c3872ea605b to your computer and use it in GitHub Desktop.
SharingContext - Step 1
<?php
declare(strict_types=1);
use Behat\Behat\Context\Environment\InitializedContextEnvironment;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
trait SharedContextTrait
{
/** @var SharingContext */
private $sharingContext;
/**
* @BeforeScenario
*/
public function gatherSharingContext(BeforeScenarioScope $scope): void
{
/** @var InitializedContextEnvironment $environment */
$environment = $scope->getEnvironment();
$this->sharingContext = $environment->getContext(SharingContext::class);
}
}
<?php
declare(strict_types=1);
use Behat\Behat\Context\Context;
use Behat\Symfony2Extension\Context\KernelAwareContext;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\KernelInterface;
use Twig\Environment;
class SharingContext implements Context, \ArrayAccess, KernelAwareContext
{
/** @var array */
private $values = [];
/** @var Environment */
private $twig;
public function setKernel(KernelInterface $kernel): void
{
/** @var ContainerInterface $container */
$container = $kernel->getContainer();
if (!$container->has('twig')) {
throw new \LogicException(
"Could not find 'twig' service. Try running 'composer req --dev twig/twig symfony/twig-bundle'."
);
}
/** @var Environment $twig */
$twig = $container->get('twig');
$this->twig = $twig;
}
public function renderTwigTemplate(string &$string): void
{
$template = $this->twig->createTemplate($string);
$string = $this->twig->render($template, $this->values);
}
public function offsetExists($offset): bool
{
return array_key_exists($offset, $this->values);
}
public function offsetGet($offset)
{
return $this->values[$offset];
}
public function offsetSet($offset, $value): void
{
$this->values[$offset] = $value;
}
public function offsetUnset($offset): void
{
unset($this->values[$offset]);
}
public function merge(array $array): void
{
$this->values = array_merge($this->values, $array);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment