Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/phpunit via strategy #100

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 2 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,32 +113,8 @@ Inject the detected language here with the following code:
<html lang="<?= Locale::getPrimaryLanguage(Locale::getDefault())?>">
```

### Disable UriPathStrategy in PHPUNIT
This is necessary (at the moment) if you want to use ``this->dispatch('my/uri');`` in your `AbstractHttpControllerTestCase` unit tests.
Otherwise, if you check for responseCode you will get `302` where it should be `200`.

Example:
```
$this->dispatch('/to/my/uri');
$this->assertResponseStatusCode(200); // this will be 302 instead of 200

$this->dispatch('/en/to/my/uri');
$this->assertResponseStatusCode(200); // this will be 302 instead of 200
```

To fix add the following to your phpunit config.

phpunit.xml:
```
<phpunit...>
...
<php>
<server name="DISABLE_URIPATHSTRATEGY" value="true" />
</php>
</phpunit>
```

Or set ``$_SERVER['DISABLE_URIPATHSTRATEGY'] = true;`` in your bootstrap file of phpunit.
### PHPUNIT configuration (as this module breaks some tests at the moment)
Have a look at [strategies documentation](docs/2.Strategies.md).

### Create a list of available locales

Expand Down
57 changes: 56 additions & 1 deletion docs/2.Strategies.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,4 +89,59 @@ To cope with such problems use AssetStrategy:

The `file_extensions` array should contain all file endings you use for your assets. URIs of files which have one of the specified extensions will not be rewritten (the example above excludes `css` and `js` files).

**Important:** Make sure to add AssetStrategy first / have AssetStrategy added with highest priority in your config. Otherwise some other strategies may rewrite the URI of an asset.
**Important:** Make sure to add AssetStrategy first / have AssetStrategy added with highest priority in your config. Otherwise some other strategies may rewrite the URI of an asset.

### PHPUNIT strategy
This is necessary (at the moment) if you want to use ``this->dispatch('my/uri');`` in your `AbstractHttpControllerTestCase` unit tests.
Otherwise, if you check for responseCode you will get `302` where it should be `200`.
More information at: https://github.com/basz/SlmLocale/issues/26

Example:
```
$this->dispatch('/to/my/uri');
$this->assertResponseStatusCode(200); // this will be 302 instead of 200

$this->dispatch('/en/to/my/uri');
$this->assertResponseStatusCode(200); // this will be 302 instead of 200
```

To fix add the following to your phpunit config.

phpunit.xml:
```
<phpunit...>
...
<php>
<server name="SLMLOCALE_DISABLE_STRATEGIES" value="true" />
</php>
</phpunit>
```

Or set ``$_SERVER['SLMLOCALE_DISABLE_STRATEGIES'] = true;`` in your bootstrap file of phpunit.

Do not forget to enable phpunit strategy in config (example):

```
'strategies' => [
'phpunit',
[
'name' => SlmLocale\Strategy\AssetStrategy::class,
'options' => [
'file_extensions' => [
'css', 'js'
]
]
],
'query',
[
'name' => \SlmLocale\Strategy\UriPathStrategy::class,
'options' => [
'redirect_when_found' => true,
'aliases' => array('de' => 'de_DE', 'en' => 'en_GB'),
]
],
'cookie',
'acceptlanguage'
],
```
**Important:** Make sure to add PhpunitStrategy first / have PhpunitStrategy added with highest priority in your config. Otherwise some other strategies may rewrite the URI of an asset.
21 changes: 19 additions & 2 deletions src/SlmLocale/Module.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,23 @@ public function getConfig()
}

public function onBootstrap(EventInterface $e)
{
$app = $e->getApplication();
$sm = $app->getServiceManager();
$detector = $sm->get(Detector::class);

$em = $app->getEventManager();
$em->attach(MvcEvent::EVENT_ROUTE, function ($e) use ($app, $detector) {
$result = $detector->detect($app->getRequest(), $app->getResponse());
if ($result instanceof ResponseInterface) {
return $result;
} else {
Locale::setDefault($result);
}
}, PHP_INT_MAX);
}

/*public function onBootstrap(EventInterface $e)
{
$app = $e->getApplication();
$sm = $app->getServiceManager();
Expand All @@ -76,13 +93,13 @@ public function onBootstrap(EventInterface $e)
*
* The listener is attached at PHP_INT_MAX to return the response as early as
* possible.
*/
*
$em = $app->getEventManager();
$em->attach(MvcEvent::EVENT_ROUTE, function ($e) use ($result) {
return $result;
}, PHP_INT_MAX);
} else {
Locale::setDefault($result);
}
}
}*/
}
44 changes: 44 additions & 0 deletions src/SlmLocale/Strategy/PhpunitStrategy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

namespace SlmLocale\Strategy;

use SlmLocale\LocaleEvent;

/**
* This class checks if running in a phpunit environment. If so and phpunit is correctly configured, it will stop event processing as we cannot properly use this module with phpunit tests at the moment.
* @SEE https://github.com/basz/SlmLocale/pull/99
*
* For configuration example have a look at README.md.
*
* Class PhpunitStrategy
* @package SlmLocale\Strategy
*/
final class PhpunitStrategy extends AbstractStrategy
{
/** @var array */
private $file_extensions = [];

public function detect(LocaleEvent $event)
{
$this->stopPropagationIfPhpunit($event);
}

public function found(LocaleEvent $event)
{
$this->stopPropagationIfPhpunit($event);
}

private function stopPropagationIfPhpunit(LocaleEvent $event)
{
if (! $this->isHttpRequest($event->getRequest())) {
return;
}

$isPhpunit = array_key_exists('SLMLOCALE_DISABLE_STRATEGIES', $_SERVER) && $_SERVER['SLMLOCALE_DISABLE_STRATEGIES'];

// if the file extension of the uri is found within the configured file_extensions, we do not rewrite and skip further processing
if ($isPhpunit) {
$event->stopPropagation();
}
}
}
2 changes: 2 additions & 0 deletions src/SlmLocale/Strategy/StrategyPluginManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ class StrategyPluginManager extends AbstractPluginManager
'query' => QueryStrategy::class,
'uripath' => UriPathStrategy::class,
'asset' => AssetStrategy::class,
'phpunit' => PhpunitStrategy::class,
];

/**
Expand All @@ -70,5 +71,6 @@ class StrategyPluginManager extends AbstractPluginManager
QueryStrategy::class => InvokableFactory::class,
UriPathStrategy::class => UriPathStrategyFactory::class,
AssetStrategy::class => InvokableFactory::class,
PhpunitStrategy::class => InvokableFactory::class,
];
}
4 changes: 0 additions & 4 deletions src/SlmLocale/Strategy/UriPathStrategy.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,6 @@ public function detect(LocaleEvent $event)

public function found(LocaleEvent $event)
{
if (array_key_exists('DISABLE_URIPATHSTRATEGY', $_SERVER) && true === $_SERVER['DISABLE_URIPATHSTRATEGY']) {
return;
}

$request = $event->getRequest();
if (! $this->isHttpRequest($request)) {
return;
Expand Down
109 changes: 109 additions & 0 deletions tests/SlmLocaleTest/Strategy/PhpunitStrategyTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
<?php
/**
* Created by PhpStorm.
* User: mfuesslin
* Date: 12.12.17
* Time: 16:15
*/

namespace SlmLocaleTest\Strategy;

use PHPUnit\Framework\TestCase;
use SlmLocale\Locale\Detector;
use SlmLocale\LocaleEvent;
use SlmLocale\Strategy\PhpunitStrategy;
use Zend\EventManager\EventManager;
use Zend\Http\PhpEnvironment\Request as HttpRequest;
use Zend\Http\PhpEnvironment\Response as HttpResponse;
use Zend\Router\Http\TreeRouteStack as HttpRouter;

class PhpunitStrategyTest extends TestCase
{
/** @var PhpunitStrategy */
private $strategy;
/** @var LocaleEvent */
private $event;
/** @var HttpRouter */
private $router;

public function setup()
{
$this->router = new HttpRouter();

$this->event = new LocaleEvent();
$this->event->setSupported(['nl', 'de', 'en']);

$this->strategy = new PhpunitStrategy();
}

public function testPreventStrategiesExecutionIfPhpunit()
{
$_SERVER['SLMLOCALE_DISABLE_STRATEGIES'] = true;

$uri = 'http://username:[email protected]:8080/some/deep/path/some.file?withsomeparam=true';
$request = new HttpRequest();
$request->setUri($uri);

$this->event->setLocale('en');
$this->event->setRequest($request);
$this->event->setResponse(new HttpResponse());

$this->strategy->found($this->event);

$statusCode = $this->event->getResponse()->getStatusCode();
$this->assertEquals(200, $statusCode);

$_SERVER['SLMLOCALE_DISABLE_STRATEGIES'] = false;
}

public function testPhpunitStrategyCanPreventOtherStrategiesExecution()
{
$_SERVER['SLMLOCALE_DISABLE_STRATEGIES'] = true;

$request = new HttpRequest();
$request->setUri('http://example.com/css/style.css');
$query = $request->getQuery();
$query->lang = 'de';
$request->setQuery($query);
$this->event->setRequest($request);

$detector = new Detector();
$detector->setEventManager(new EventManager());
$detector->setSupported(['nl', 'de', 'en']);
$detector->setDefault('en');
$detector->addStrategy($this->strategy);
$detector->addStrategy(new \SlmLocale\Strategy\QueryStrategy());
$response = new HttpResponse();

$result = $detector->detect($request, $response);
$this->assertEquals('en', $result);

$_SERVER['SLMLOCALE_DISABLE_STRATEGIES'] = false;
}

public function testPhpunitStrategyDoesNotPreventOtherStrategiesExecution()
{
// can also be null / not set
$_SERVER['SLMLOCALE_DISABLE_STRATEGIES'] = false;

$request = new HttpRequest();
$request->setUri('http://example.com/css/style.css');
$query = $request->getQuery();
$query->lang = 'de';
$request->setQuery($query);
$this->event->setRequest($request);

$detector = new Detector();
$detector->setEventManager(new EventManager());
$detector->setSupported(['nl', 'de', 'en']);
$detector->setDefault('en');
$detector->addStrategy($this->strategy);
$detector->addStrategy(new \SlmLocale\Strategy\QueryStrategy());
$response = new HttpResponse();

$result = $detector->detect($request, $response);
$this->assertEquals('de', $result);

$_SERVER['SLMLOCALE_DISABLE_STRATEGIES'] = false;
}
}
22 changes: 0 additions & 22 deletions tests/SlmLocaleTest/Strategy/UriPathStrategyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -348,28 +348,6 @@ public function testAssembleWorksWithAliasesToo()
$this->assertEquals($expected, $actual);
}

public function testDisableUriPathStrategyPhpunit()
{
$_SERVER['DISABLE_URIPATHSTRATEGY'] = true;

$uri = 'http://username:[email protected]:8080/some/deep/path/some.file?withsomeparam=true';
$request = new HttpRequest();
$request->setUri($uri);

$this->event->setLocale('en');
$this->event->setRequest($request);
$this->event->setResponse(new HttpResponse());

$this->strategy->found($this->event);

$statusCode = $this->event->getResponse()->getStatusCode();
$header = $this->event->getResponse()->getHeaders()->get('Location');
$expected = 'Location: http://username:[email protected]:8080/en/some/deep/path/some.file?withsomeparam=true';
$this->assertEquals(200, $statusCode);

$_SERVER['DISABLE_URIPATHSTRATEGY'] = false;
}

protected function getPluginManager($console = false)
{
$sl = new ServiceManager();
Expand Down