diff --git a/.gitignore b/.gitignore index 2f46234..06a6676 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ vendor/ composer.phar composer.lock +phpunit.xml +report/ \ No newline at end of file diff --git a/LocaleGuesser/BrowserLocaleGuesser.php b/LocaleGuesser/BrowserLocaleGuesser.php index d3720b5..d4580f8 100644 --- a/LocaleGuesser/BrowserLocaleGuesser.php +++ b/LocaleGuesser/BrowserLocaleGuesser.php @@ -25,11 +25,6 @@ class BrowserLocaleGuesser implements LocaleGuesserInterface */ private $identifiedLocale; - /** - * @var bool - */ - private $intlExtension; - /** * @var MetaValidator */ @@ -38,13 +33,11 @@ class BrowserLocaleGuesser implements LocaleGuesserInterface /** * Constructor * - * @param MetaValidator $metaValidator MetaValidator - * @param bool $intlExtensionInstalled Wether the intl extension is installed + * @param MetaValidator $metaValidator MetaValidator */ - public function __construct(MetaValidator $metaValidator, $intlExtensionInstalled = false) + public function __construct(MetaValidator $metaValidator) { $this->metaValidator = $metaValidator; - $this->intlExtension = $intlExtensionInstalled; } /** @@ -87,23 +80,6 @@ public function guessLocale(Request $request) return false; } - /** - * Fallback function for fetching the primary language, if no intl extension is installed. - * - * @param string $locale - * - * @return null|string - */ - private function getPrimaryLanguage($locale) - { - if ($this->intlExtension) { - return \Locale::getPrimaryLanguage($locale); - } - $splittedLocale = explode('_', $locale); - - return count($splittedLocale) > 1 ? $splittedLocale[0] : $locale; - } - /** * {@inheritDoc} */ diff --git a/LocaleGuesser/LocaleGuesserManager.php b/LocaleGuesser/LocaleGuesserManager.php index 18d0888..3814b8a 100644 --- a/LocaleGuesser/LocaleGuesserManager.php +++ b/LocaleGuesser/LocaleGuesserManager.php @@ -40,6 +40,7 @@ class LocaleGuesserManager * @var array */ private $preferredLocales; + /** * @var LoggerInterface */ diff --git a/LocaleGuesser/QueryLocaleGuesser.php b/LocaleGuesser/QueryLocaleGuesser.php index b3f8da7..fbea3de 100644 --- a/LocaleGuesser/QueryLocaleGuesser.php +++ b/LocaleGuesser/QueryLocaleGuesser.php @@ -28,11 +28,6 @@ class QueryLocaleGuesser implements LocaleGuesserInterface */ private $identifiedLocale; - /** - * @var Request - */ - private $request; - /** * Constructor * diff --git a/Session/LocaleSession.php b/Session/LocaleSession.php index 0cc3a41..dbf0621 100644 --- a/Session/LocaleSession.php +++ b/Session/LocaleSession.php @@ -64,11 +64,12 @@ public function setLocale($locale) /** * Returns the locale * - * @param string $locale + * @param $locale + * @return string */ public function getLocale($locale) { - $this->session->get($this->sessionVar, $locale); + return $this->session->get($this->sessionVar, $locale); } /** diff --git a/Tests/DependencyInjection/Compiler/GuesserCompilerPassTest.php b/Tests/DependencyInjection/Compiler/GuesserCompilerPassTest.php new file mode 100644 index 0000000..cdbcefe --- /dev/null +++ b/Tests/DependencyInjection/Compiler/GuesserCompilerPassTest.php @@ -0,0 +1,63 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that is distributed with this source code. + */ +namespace Lunetics\LocaleBundle\Tests\DependencyInjection\Compiler; + +use Lunetics\LocaleBundle\DependencyInjection\Compiler\GuesserCompilerPass; +use Symfony\Component\DependencyInjection\ContainerBuilder; + +/** + * @author Kevin Archer + */ +class GuesserCompilerPassTest extends \PHPUnit_Framework_TestCase +{ + public function testProcess() + { + $container = new ContainerBuilder(); + + $container + ->register('lunetics_locale.guesser_manager') + ; + + $container + ->register('lunetics_locale.query_guesser') + ->addTag('lunetics_locale.guesser', array('alias' => 'query')) + ; + + $container + ->register('lunetics_locale.browser_guesser') + ->addTag('lunetics_locale.guesser', array('alias' => 'browser')) + ; + + $container->setParameter('lunetics_locale.guessing_order', array('query')); + + $this->process($container); + + $methodCalls = $container + ->getDefinition('lunetics_locale.guesser_manager') + ->getMethodCalls(); + + $this->assertCount( + 1, + $methodCalls + ); + + $methodName = $methodCalls[0][0]; + $argument = $methodCalls[0][1][1]; + + $this->assertEquals('addGuesser', $methodName); + $this->assertEquals('query', $argument); + } + + protected function process(ContainerBuilder $container) + { + $pass = new GuesserCompilerPass(); + $pass->process($container); + } +} diff --git a/Tests/DependencyInjection/LuneticsLocaleExtensionTest.php b/Tests/DependencyInjection/LuneticsLocaleExtensionTest.php index 9f0406d..dcb3523 100644 --- a/Tests/DependencyInjection/LuneticsLocaleExtensionTest.php +++ b/Tests/DependencyInjection/LuneticsLocaleExtensionTest.php @@ -13,119 +13,90 @@ use Lunetics\LocaleBundle\DependencyInjection\LuneticsLocaleExtension; use Symfony\Component\Yaml\Parser; +/** + * @author Kevin Archer + */ class LuneticsLocaleExtensionTest extends \PHPUnit_Framework_TestCase { - protected $configuration; - - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - */ - public function testBundleLoadThrowsExceptionUnlessDetectorsOrderIsSet() + public function testLoad() { $loader = new LuneticsLocaleExtension(); - $config = $this->getEmptyConfig(); - unset($config['guessing_order']); - $loader->load(array($config), new ContainerBuilder()); + $container = new ContainerBuilder(); + + $configs = $this->getFullConfig(); + + $loader->load($configs, $container); + + $this->assertTrue($container->hasParameter('lunetics_locale.allowed_locales')); + $this->assertTrue($container->hasParameter('lunetics_locale.intl_extension_installed')); + + if (extension_loaded('intl')) { + $this->assertEquals(array(), $container->getParameter('lunetics_locale.intl_extension_fallback.iso3166')); + $this->assertEquals(array(), $container->getParameter('lunetics_locale.intl_extension_fallback.iso639')); + $this->assertEquals(array(), $container->getParameter('lunetics_locale.intl_extension_fallback.script')); + } else { + $this->assertGreaterThan(0, count($container->getParameter('lunetics_locale.intl_extension_fallback.iso3166'))); + $this->assertGreaterThan(0, count($container->getParameter('lunetics_locale.intl_extension_fallback.iso639'))); + $this->assertGreaterThan(0, count($container->getParameter('lunetics_locale.intl_extension_fallback.script'))); + } + + $resources = $container->getResources(); + + $this->assertContains('validator.xml', $resources[0]->getResource()); + $this->assertContains('guessers.xml', $resources[1]->getResource()); + $this->assertContains('services.xml', $resources[2]->getResource()); + $this->assertContains('switcher.xml', $resources[3]->getResource()); + $this->assertContains('form.xml', $resources[4]->getResource()); } /** * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException + * @expectedExceptionMessage The child node "guessing_order" at path "lunetics_locale" must be configured. */ - public function testBundleLoadThrowsExceptionIfNonBooleanValueIsSet() + public function testBundleLoadThrowsExceptionUnlessGuessingOrderIsSet() { $loader = new LuneticsLocaleExtension(); - $config = $this->getEmptyConfig(); - $config['router_guesser']['check_query'] = 'hello'; - $loader->load(array($config), new ContainerBuilder()); + $loader->load(array(), new ContainerBuilder()); } - /** - * @return ContainerBuilder - */ - protected function createEmptyConfiguration() + public function testGetAlias() { - $this->configuration = new ContainerBuilder(); $loader = new LuneticsLocaleExtension(); - $config = $this->getEmptyConfig(); - $loader->load(array($config), $this->configuration); - $this->assertTrue($this->configuration instanceof ContainerBuilder); + $this->assertEquals('lunetics_locale', $loader->getAlias()); } - /** - * @return ContainerBuilder - */ - protected function createFullConfiguration() + public function testBindParameters() { - $this->configuration = new ContainerBuilder(); $loader = new LuneticsLocaleExtension(); - $config = $this->getFullConfig(); - $loader->load(array($config), $this->configuration); - $this->assertTrue($this->configuration instanceof ContainerBuilder); - } + $container = new ContainerBuilder(); - /** - * getEmptyConfig - * - * @return array - */ - protected function getEmptyConfig() - { - $yaml = << 'value', + ); + + $loader->bindParameters($container, $loader->getAlias(), $config); - return $parser->parse($yaml); + $this->assertTrue($container->hasParameter('lunetics_locale.key')); + $this->assertEquals('value', $container->getParameter('lunetics_locale.key')); } protected function getFullConfig() { $yaml = <<parse($yaml); } - - private function assertAlias($value, $key) - { - $this->assertEquals($value, (string) $this->configuration->getAlias($key), sprintf('%s alias is correct', $key)); - } - - private function assertParameter($value, $key) - { - $this->assertEquals($value, $this->configuration->getParameter($key), sprintf('%s parameter is correct', $key)); - } - - private function assertHasDefinition($id) - { - $this->assertTrue(($this->configuration->hasDefinition($id) ?: $this->configuration->hasAlias($id))); - } - - private function assertNotHasDefinition($id) - { - $this->assertFalse(($this->configuration->hasDefinition($id) ?: $this->configuration->hasAlias($id))); - } - - protected function tearDown() - { - unset($this->configuration); - } } diff --git a/Tests/EventListener/LocaleListenerTest.php b/Tests/EventListener/LocaleListenerTest.php index bdd6415..5eaa9f0 100644 --- a/Tests/EventListener/LocaleListenerTest.php +++ b/Tests/EventListener/LocaleListenerTest.php @@ -24,6 +24,7 @@ use Lunetics\LocaleBundle\LocaleGuesser\QueryLocaleGuesser; use Lunetics\LocaleBundle\Validator\MetaValidator; use Lunetics\LocaleBundle\LocaleBundleEvents; +use Symfony\Component\HttpKernel\KernelEvents; class LocaleListenerTest extends \PHPUnit_Framework_TestCase @@ -171,14 +172,76 @@ public function testAjaxRequestsAreHandled() $this->assertEquals('fr', $request->getLocale()); } + public function testOnLocacleDetectedSetVaryHeader() + { + $listener = $this->getListener(); + + $response = $this->getMockResponse(); + $response + ->expects($this->once()) + ->method('setVary') + ->with('Accept-Language') + ->will($this->returnValue($response)); + ; + + $filterResponseEvent = $this->getMockFilterResponseEvent(); + $filterResponseEvent + ->expects($this->once()) + ->method('getResponse') + ->will($this->returnValue($response)) + ; + + $listener->onLocaleDetectedSetVaryHeader($filterResponseEvent); + + } + + public function testLogEvent() + { + $message = 'Setting [ 1 ] as locale for the (Sub-)Request'; + + $request = $this->getEmptyRequest(); + + $guesserManager = $this->getMockGuesserManager(); + $guesserManager + ->expects($this->once()) + ->method('runLocaleGuessing') + ->with($request) + ->will($this->returnValue(true)); + + + $logger = $this->getMockLogger(); + $logger + ->expects($this->once()) + ->method('info') + ->with($message, array()); + + $listener = $this->getListener('en', $guesserManager, $logger); + + $event = $this->getEvent($request); + + $listener->onKernelRequest($event); + } + + public function testGetSubscribedEvents() + { + $subscribedEvents = LocaleListener::getSubscribedEvents(); + + $this->assertEquals(array(array('onKernelRequest', 24)), $subscribedEvents[KernelEvents::REQUEST]); + $this->assertEquals(array('onLocaleDetectedSetVaryHeader'), $subscribedEvents[KernelEvents::RESPONSE]); + } + private function getEvent(Request $request) { return new GetResponseEvent($this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'), $request, HttpKernelInterface::MASTER_REQUEST); } - private function getListener($locale, $manager) + private function getListener($locale = 'en', $manager = null, $logger = null) { - $listener = new LocaleListener($locale, $manager); + if (null === $manager) { + $manager = $this->getGuesserManager(); + } + + $listener = new LocaleListener($locale, $manager, $logger); $listener->setEventDispatcher(new \Symfony\Component\EventDispatcher\EventDispatcher()); return $listener; @@ -208,10 +271,19 @@ private function getGuesserManager($order = array(1 => 'router', 2 => 'browser') return $manager; } + private function getMockGuesserManager() + { + return $this + ->getMockBuilder('Lunetics\LocaleBundle\LocaleGuesser\LocaleGuesserManager') + ->disableOriginalConstructor() + ->getMock() + ; + } + /** * @return LocaleGuesserInterface */ - private function getGuesserMock() + private function getMockGuesser() { $mock = $this->getMockBuilder('Lunetics\LocaleBundle\LocaleGuesser\LocaleGuesserInterface')->disableOriginalConstructor()->getMock(); @@ -259,4 +331,28 @@ private function getEmptyRequest() return $request; } + + private function getMockRequest() + { + return $this->getMock('Symfony\Component\HttpFoundation\Request'); + } + + private function getMockResponse() + { + return $this->getMock('Symfony\Component\HttpFoundation\Response'); + } + + private function getMockFilterResponseEvent() + { + return $this + ->getMockBuilder('Symfony\Component\HttpKernel\Event\FilterResponseEvent') + ->disableOriginalConstructor() + ->getMock() + ; + } + + private function getMockLogger() + { + return $this->getMock('Symfony\Component\HttpKernel\Log\LoggerInterface'); + } } diff --git a/Tests/EventListener/LocaleUpdateTest.php b/Tests/EventListener/LocaleUpdateTest.php index 0f663ec..8b45d6c 100644 --- a/Tests/EventListener/LocaleUpdateTest.php +++ b/Tests/EventListener/LocaleUpdateTest.php @@ -10,6 +10,7 @@ namespace Lunetics\LocaleBundle\Tests\EventListener; +use Lunetics\LocaleBundle\LocaleBundleEvents; use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\HttpKernel\HttpKernelInterface; @@ -83,7 +84,14 @@ public function testCookieIsNotUpdatedWithFalseSetCookieOnChange() public function testUpdateCookieOnResponse() { $event = $this->getEvent($this->getRequest()); - $listener = $this->getLocaleUpdateListener(); + + $logger = $this->getMockLogger(); + $logger + ->expects($this->once()) + ->method('info') + ->with('Locale Cookie set to [ es ]'); + + $listener = $this->getLocaleUpdateListener(array(), false, $logger); $reflectionClass = new \ReflectionClass($listener); $property = $reflectionClass->getProperty('locale'); @@ -103,7 +111,14 @@ public function testUpdateCookieOnResponse() public function testUpdateSession() { $this->session->setLocale('el'); - $listener = $this->getLocaleUpdateListener(array('session')); + + $logger = $this->getMockLogger(); + $logger + ->expects($this->once()) + ->method('info') + ->with('Session var \'lunetics_locale\' set to [ tr ]'); + + $listener = $this->getLocaleUpdateListener(array('session'), false, $logger); $reflectionClass = new \ReflectionClass($listener); $property = $reflectionClass->getProperty('locale'); @@ -139,17 +154,25 @@ public function testNotUpdateSessionSameLocale() $this->assertFalse($listener->updateSession()); } + public function testGetSubscribedEvents() + { + $subcribedEvents = LocaleUpdateListener::getSubscribedEvents(); + + $this->assertEquals(array('onLocaleChange'), $subcribedEvents[LocaleBundleEvents::onLocaleChange]); + } + private function getFilterLocaleSwitchEvent($withCookieSet = true, $locale = 'fr') { return new FilterLocaleSwitchEvent($this->getRequest($withCookieSet), $locale); } - private function getLocaleUpdateListener($registeredGuessers = array(), $updateCookie = false) + private function getLocaleUpdateListener($registeredGuessers = array(), $updateCookie = false, $logger = null) { $listener = new LocaleUpdateListener($this->getLocaleCookie($updateCookie), $this->session, $this->dispatcher, - $registeredGuessers); + $registeredGuessers, + $logger); return $listener; } @@ -173,4 +196,9 @@ private function getRequest($withCookieSet = false) return $request; } + + private function getMockLogger() + { + return $this->getMock('Symfony\Component\HttpKernel\Log\LoggerInterface'); + } } diff --git a/Tests/Form/Extension/Type/LocaleTypeTest.php b/Tests/Form/Extension/Type/LocaleTypeTest.php new file mode 100644 index 0000000..cdd5393 --- /dev/null +++ b/Tests/Form/Extension/Type/LocaleTypeTest.php @@ -0,0 +1,60 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that is distributed with this source code. + */ +namespace Lunetics\LocaleBundle\Tests\Form\Extension\Type; + +use Lunetics\LocaleBundle\Form\Extension\Type\LocaleType; + +/** + * @author Kevin Archer + */ +class LocaleTypeTest extends \PHPUnit_Framework_TestCase +{ + public function testSetDefaultOptions() + { + $choiceList = $this->getMockLocaleChoiceList(); + + $resolver = $this->getMockOptionsResolverInterface(); + $resolver + ->expects($this->once()) + ->method('setDefaults') + ->with(array('choice_list' => $choiceList)); + + $type = new LocaleType($choiceList); + $type->setDefaultOptions($resolver); + } + + public function testGetParent() + { + $type = new LocaleType($this->getMockLocaleChoiceList()); + + $this->assertEquals('choice', $type->getParent()); + } + + public function testGetName() + { + $type = new LocaleType($this->getMockLocaleChoiceList()); + + $this->assertEquals('lunetics_locale', $type->getName()); + } + + protected function getMockLocaleChoiceList() + { + return $this + ->getMockBuilder('Lunetics\LocaleBundle\Form\Extension\ChoiceList\LocaleChoiceList') + ->disableOriginalConstructor() + ->getMock() + ; + } + + protected function getMockOptionsResolverInterface() + { + return $this->getMock('Symfony\Component\OptionsResolver\OptionsResolverInterface'); + } +} \ No newline at end of file diff --git a/Tests/LocaleGuesser/BrowserLocaleGuesserTest.php b/Tests/LocaleGuesser/BrowserLocaleGuesserTest.php index 8f0a9ef..00f65ee 100644 --- a/Tests/LocaleGuesser/BrowserLocaleGuesserTest.php +++ b/Tests/LocaleGuesser/BrowserLocaleGuesserTest.php @@ -53,11 +53,6 @@ public function testLocaleIsIdentifiedFromBrowserTestFallbackForNoIntlExtension( $request = $this->getRequestWithBrowserPreferences(); $guesser = $this->getGuesser($metaValidator); - $reflectionClass = new \ReflectionClass($guesser); - $property = $reflectionClass->getProperty('intlExtension'); - $property->setAccessible(true); - $property->setValue($guesser, false); - $metaValidator->expects($this->once()) ->method('isAllowed') ->with('fr_FR') @@ -86,11 +81,6 @@ public function testLocaleIsNotIdentifiedIsNoMatchedLanguageTestFallbackForNoInt $request = $this->getRequestWithBrowserPreferences(); $guesser = $this->getGuesser($metaValidator); - $reflectionClass = new \ReflectionClass($guesser); - $property = $reflectionClass->getProperty('intlExtension'); - $property->setAccessible(true); - $property->setValue($guesser, false); - $metaValidator->expects($this->any()) ->method('isAllowed') ->will($this->returnValue(false)); @@ -118,8 +108,9 @@ public function correctLocales() /** * @dataProvider correctLocales * - * @param array $allowedLocales + * @param array $allowedLocales * @param string $result + * @param bool $strict */ public function testEnsureCorrectLocaleForAllowedLocales($allowedLocales, $result, $strict) { diff --git a/Tests/LocaleGuesser/LocaleGuesserManagerTest.php b/Tests/LocaleGuesser/LocaleGuesserManagerTest.php index 0798d76..9bba72c 100644 --- a/Tests/LocaleGuesser/LocaleGuesserManagerTest.php +++ b/Tests/LocaleGuesser/LocaleGuesserManagerTest.php @@ -37,8 +37,20 @@ public function testLocaleIsIdentifiedByTheQueryGuessingService() ->with('fr') ->will($this->returnValue(true)); + $logger = $this->getMockLogger(); + $logger + ->expects($this->at(0)) + ->method('info', array()) + ->with('Locale Query Guessing Service Loaded') + ; + $logger + ->expects($this->at(1)) + ->method('info', array()) + ->with('Locale has been identified by guessing service: ( Query )') + ; + $order = array(0 => 'query', 1 => 'router'); - $manager = new LocaleGuesserManager($order); + $manager = new LocaleGuesserManager($order, $logger); $manager->addGuesser(new RouterLocaleGuesser($metaValidator), 'router'); $manager->addGuesser(new QueryLocaleGuesser($metaValidator), 'query'); @@ -72,6 +84,39 @@ public function testLocaleIsNotIdentifiedIfNoQueryParamsExist() $this->assertFalse($guessing); } + public function testGetPreferredLocales() + { + $manager = new LocaleGuesserManager(array()); + $value = uniqid('preferredLocales:'); + + $reflectionsClass = new \ReflectionClass(get_class($manager)); + $property = $reflectionsClass->getProperty('preferredLocales'); + $property->setAccessible(true); + $property->setValue($manager, $value); + + $this->assertEquals($value, $manager->getPreferredLocales()); + } + + public function testGetGuessingOrder() + { + $order = array(0 => 'query', 1 => 'router'); + + $manager = new LocaleGuesserManager($order); + + $this->assertEquals($order, $manager->getGuessingOrder()); + } + + public function testRemoveGuesser() + { + $order = array(0 => 'query', 1 => 'router'); + $manager = new LocaleGuesserManager($order); + + $manager->addGuesser($this->getGuesserMock(), 'mock'); + + $manager->removeGuesser('mock'); + $this->assertNull($manager->getGuesser('mock')); + } + private function getRequestWithLocaleQuery($locale = 'en') { $request = Request::create(' / hello - world', 'GET'); @@ -106,4 +151,10 @@ private function getMetaValidatorMock() return $mock; } + + private function getMockLogger() + { + return $this->getMock('Symfony\Component\HttpKernel\Log\LoggerInterface'); + } + } diff --git a/Tests/LocaleGuesser/SessionLocaleGuesserTest.php b/Tests/LocaleGuesser/SessionLocaleGuesserTest.php index 4b21c1a..53e9820 100644 --- a/Tests/LocaleGuesser/SessionLocaleGuesserTest.php +++ b/Tests/LocaleGuesser/SessionLocaleGuesserTest.php @@ -17,7 +17,6 @@ class SessionLocaleGuesserTest extends \PHPUnit_Framework_TestCase { - public function testGuesserExtendsInterface() { $request = $this->getRequestWithSessionLocale(); @@ -25,6 +24,15 @@ public function testGuesserExtendsInterface() $this->assertTrue($guesser instanceof LocaleGuesserInterface); } + public function testGuessLocaleWithoutSessionVariable() + { + $request = $this->getRequestWithSessionLocale(); + + $guesser = $this->getGuesser(); + + $this->assertFalse($guesser->guessLocale($request)); + } + public function testLocaleIsRetrievedFromSessionIfSet() { $request = $this->getRequestWithSessionLocale(); @@ -53,8 +61,25 @@ public function testLocaleIsNotRetrievedFromSessionIfInvalid() $this->assertFalse($guesser->getIdentifiedLocale()); } - private function getGuesser($session = null, $metaValidator) + public function testSetSessionLocale() { + $locale = uniqid('locale:'); + + $guesser = $this->getGuesser(); + $guesser->setSessionLocale($locale, true); + + $this->assertAttributeContains($locale, 'session', $guesser); + } + + private function getGuesser($session = null, $metaValidator = null) + { + if (null === $session) { + $session = $this->getSession(); + } + + if (null === $metaValidator) { + $metaValidator = $this->getMetaValidatorMock(); + } return new SessionLocaleGuesser($session, $metaValidator); } diff --git a/Tests/LocaleInformation/LocaleInformationTest.php b/Tests/LocaleInformation/LocaleInformationTest.php index 8e17068..15c01a9 100644 --- a/Tests/LocaleInformation/LocaleInformationTest.php +++ b/Tests/LocaleInformation/LocaleInformationTest.php @@ -109,7 +109,24 @@ public function testGetAllAllowedLanguagesStrict($intlExtension) } } - public function getGuesserManagerMock() + public function testGetPreferredLocales() + { + $preferredLocale = array('en', 'de'); + $allowedLocales = array('en', 'fr', 'es'); + + $guesserManager = $this->getGuesserManagerMock(); + $guesserManager + ->expects($this->once()) + ->method('getPreferredLocales') + ->will($this->returnValue($preferredLocale)) + ; + + $info = new LocaleInformation($this->getMetaValidator($allowedLocales), $guesserManager, $allowedLocales); + + $this->assertEquals(array('en'), $info->getPreferredLocales()); + } + + protected function getGuesserManagerMock() { return $this->getMockBuilder('Lunetics\LocaleBundle\LocaleGuesser\LocaleGuesserManager')->disableOriginalConstructor()->getMock(); } diff --git a/Tests/LuneticsLocaleBundleTest.php b/Tests/LuneticsLocaleBundleTest.php new file mode 100644 index 0000000..922ff88 --- /dev/null +++ b/Tests/LuneticsLocaleBundleTest.php @@ -0,0 +1,45 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that is distributed with this source code. + */ +namespace Lunetics\LocaleBundle\Tests; + +use Lunetics\LocaleBundle\DependencyInjection\Compiler\GuesserCompilerPass; +use Lunetics\LocaleBundle\DependencyInjection\Compiler\RouterResourcePass; +use Lunetics\LocaleBundle\LuneticsLocaleBundle; + +/** + * @author Kevin Archer + */ +class LuneticsLocaleBundleTest extends \PHPUnit_Framework_TestCase +{ + public function testBuild() + { + $container = $this->getMockContainer(); + + $container + ->expects($this->at(0)) + ->method('addCompilerPass') + ->with(new GuesserCompilerPass()) + ; + + $container + ->expects($this->at(1)) + ->method('addCompilerPass') + ->with(new RouterResourcePass()) + ; + + $bundle = new LuneticsLocaleBundle(); + $bundle->build($container); + } + + protected function getMockContainer() + { + return $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder'); + } +} diff --git a/Tests/Session/LocaleSessionTest.php b/Tests/Session/LocaleSessionTest.php new file mode 100644 index 0000000..81da578 --- /dev/null +++ b/Tests/Session/LocaleSessionTest.php @@ -0,0 +1,79 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that is distributed with this source code. + */ +namespace Lunetics\LocaleBundle\Tests\LocaleInformation; + +use Lunetics\LocaleBundle\Session\LocaleSession; + +/** + * @author Kevin Archer + */ +class LocaleSessionTest extends \PHPUnit_Framework_TestCase +{ + public function testHasLocaleChanged() + { + $localeEn = uniqid('en:'); + $localeFr = uniqid('fr:'); + + $session = $this->getMockSession(); + $session + ->expects($this->at(0)) + ->method('get') + ->with('lunetics_locale') + ->will($this->returnValue($localeEn)); + + $session + ->expects($this->at(1)) + ->method('get') + ->with('lunetics_locale') + ->will($this->returnValue($localeFr)); + + $localeSession = new LocaleSession($session); + + $this->assertFalse($localeSession->hasLocaleChanged($localeEn)); + $this->assertTrue($localeSession->hasLocaleChanged($localeEn)); + } + + public function testSetGetLocale() + { + $locale = uniqid('locale:'); + + $session = $this->getMockSession(); + + $session + ->expects($this->at(0)) + ->method('set') + ->with('lunetics_locale', $locale) + ; + + $session + ->expects($this->at(1)) + ->method('get') + ->with('lunetics_locale', $locale) + ->will($this->returnValue($locale)) + ; + + $localeSession = new LocaleSession($session); + + $localeSession->setLocale($locale); + $this->assertEquals($locale, $localeSession->getLocale($locale)); + } + + public function testGetSessionVar() + { + $localeSession = new LocaleSession($this->getMockSession()); + + $this->assertEquals('lunetics_locale', $localeSession->getSessionVar()); + } + + public function getMockSession() + { + return $this->getMock('Symfony\Component\HttpFoundation\Session\Session'); + } +} \ No newline at end of file diff --git a/Tests/Templating/Helper/LocaleSwitchHelperTest.php b/Tests/Templating/Helper/LocaleSwitchHelperTest.php new file mode 100644 index 0000000..cc213c8 --- /dev/null +++ b/Tests/Templating/Helper/LocaleSwitchHelperTest.php @@ -0,0 +1,49 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that is distributed with this source code. + */ +namespace Lunetics\LocaleBundle\Tests\Templating\Helper; + +use Lunetics\LocaleBundle\Templating\Helper\LocaleSwitchHelper; + +/** + * @author Kevin Archer + */ +class LocaleSwitchHelperTest extends \PHPUnit_Framework_TestCase +{ + public function testRenderSwitch() + { + $template = uniqid('template:'); + + $templating = $this->getMockEngineInterface(); + $templating + ->expects($this->once()) + ->method('render') + ->with($template, array()) + ->will($this->returnValue($template)) + ; + + $localeSwitchHelper = new LocaleSwitchHelper($templating, $template); + + $this->assertEquals($template, $localeSwitchHelper->renderSwitch()); + } + + public function testGetName() + { + $templating = $this->getMockEngineInterface(); + + $localeSwitchHelper = new LocaleSwitchHelper($templating, null); + + $this->assertEquals('locale_switch_helper', $localeSwitchHelper->getName()); + } + + protected function getMockEngineInterface() + { + return $this->getMock('Symfony\Component\Templating\EngineInterface'); + } +} diff --git a/Tests/Twig/Extension/LocaleSwitcherExtensionTest.php b/Tests/Twig/Extension/LocaleSwitcherExtensionTest.php new file mode 100644 index 0000000..5777429 --- /dev/null +++ b/Tests/Twig/Extension/LocaleSwitcherExtensionTest.php @@ -0,0 +1,111 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that is distributed with this source code. + */ +namespace Lunetics\LocaleBundle\Tests\Twig\Extension; + +use Lunetics\LocaleBundle\Twig\Extension\LocaleSwitcherExtension; +use Symfony\Component\DependencyInjection\ContainerBuilder; + +/** + * @covers \Lunetics\LocaleBundle\Twig\Extension\LocaleSwitcherExtension + * + * @author Kevin Archer + */ +class LocaleSwitcherExtensionTest extends \PHPUnit_Framework_TestCase +{ + public function testGetFunctions() + { + $container = new ContainerBuilder(); + $extension = new LocaleSwitcherExtension($container); + + $functions = $extension->getFunctions(); + + /** @var \Twig_Function_Method $twigExtension */ + $twigExtension = $functions['locale_switcher']; + + $this->assertInstanceOf('Twig_Function_Method', $twigExtension); + $callable = $twigExtension->getCallable(); + $this->assertEquals('renderSwitcher', $callable[1]); + $this->assertEquals(array('html'), $twigExtension->getSafe(new \Twig_Node())); + } + + public function testGetName() + { + $container = new ContainerBuilder(); + $extension = new LocaleSwitcherExtension($container); + + $this->assertEquals('locale_switcher', $extension->getName()); + } + + public function testRenderSwitcher() + { + $template = uniqid('template:'); + + $router = $this->getMockRouter(); + + $request = $this->getMockRequest(); + $request->attributes = $this->getMockParameterBag(); + + $query = $this->getMockParameterBag(); + $query + ->expects($this->once()) + ->method('all') + ->will($this->returnValue(array())) + ; + + $request->query = $query; + + $switcherHelper = $this->getMockSwitcherHelper(); + $switcherHelper + ->expects($this->once()) + ->method('renderSwitch') + ->will($this->returnValue($template)) + ; + + $container = new ContainerBuilder(); + $container->setParameter('lunetics_locale.switcher.show_current_locale', true); + $container->setParameter('lunetics_locale.switcher.use_controller', true); + $container->setParameter('lunetics_locale.allowed_locales', array('en', 'fr')); + $container->set('request', $request); + $container->set('router', $router); + + $container->set('lunetics_locale.switcher_helper', $switcherHelper); + + $extension = new LocaleSwitcherExtension($container); + $this->assertEquals($template, $extension->renderSwitcher()); + } + + protected function getMockRequest() + { + return $this->getMock('Symfony\Component\HttpFoundation\Request'); + } + + protected function getMockRouter() + { + return $this + ->getMockBuilder('Symfony\Component\Routing\Router') + ->disableOriginalConstructor() + ->getMock() + ; + } + + protected function getMockParameterBag() + { + return $this->getMock('Symfony\Component\HttpFoundation\ParameterBag'); + } + + protected function getMockSwitcherHelper() + { + return $this + ->getMockBuilder('Lunetics\LocaleBundle\Templating\Helper\LocaleSwitchHelper') + ->disableOriginalConstructor() + ->getMock() + ; + } +} diff --git a/Tests/Validator/LocaleAllowedValidatorTest.php b/Tests/Validator/LocaleAllowedValidatorTest.php index 2146517..5edaac1 100644 --- a/Tests/Validator/LocaleAllowedValidatorTest.php +++ b/Tests/Validator/LocaleAllowedValidatorTest.php @@ -130,6 +130,23 @@ public function testLocaleIsNotAllowedStrict($intlExtension) $this->getLocaleValidator(array('en_US', 'de_DE'), true, $intlExtension)->validate('de', $constraint); } + /** + * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException + */ + public function testValidateThrowsUnexpectedTypeException() + { + $validator = new LocaleAllowedValidator(); + $validator->validate(array(), $this->getMockConstraint()); + } + + public function testValidateEmptyLocale() + { + $validator = new LocaleAllowedValidator(); + + $validator->validate(null, $this->getMockConstraint()); + $validator->validate('', $this->getMockConstraint()); + } + /** * Returns an ExecutionContext Mock * @@ -148,11 +165,16 @@ private function getContext() * * @return LocaleAllowedValidator */ - private function getLocaleValidator($allowedLocales = array(), $strictMode = false) + private function getLocaleValidator($allowedLocales = array(), $strictMode = false, $intlExtension = false) { - $validator = new LocaleAllowedValidator($allowedLocales, $strictMode); + $validator = new LocaleAllowedValidator($allowedLocales, $strictMode, $intlExtension); $validator->initialize($this->context); return $validator; } + + protected function getMockConstraint() + { + return $this->getMock('Symfony\Component\Validator\Constraint'); + } } diff --git a/Tests/Validator/LocaleValidatorTest.php b/Tests/Validator/LocaleValidatorTest.php index 8ca8e5d..125e94a 100644 --- a/Tests/Validator/LocaleValidatorTest.php +++ b/Tests/Validator/LocaleValidatorTest.php @@ -119,7 +119,6 @@ public function testLocaleWithScriptValid($intlExtension) $this->context->expects($this->never()) ->method('addViolation'); $this->getLocaleValidator($intlExtension)->validate('zh_Hant_HK', $constraint); - } /** @@ -133,13 +132,32 @@ public function testLocaleIsInvalid($intlExtension) { $constraint = new Locale(); // Need to distinguish, since the intl fallback allows every combination of languages, script and regions - $this->context->expects($this->exactly(1)) - ->method('addViolation'); + $this->context->expects($this->exactly(3)) + ->method('addViolation'); + $this->getLocaleValidator($intlExtension)->validate('foobar', $constraint); $this->getLocaleValidator($intlExtension)->validate('de_FR', $constraint); $this->getLocaleValidator($intlExtension)->validate('fr_US', $constraint); + $this->getLocaleValidator($intlExtension)->validate('foo_bar', $constraint); + $this->getLocaleValidator($intlExtension)->validate('foo_bar_baz', $constraint); + + } + + /** + * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException + */ + public function testValidateThrowsUnexpectedTypeException() + { + $validator = new LocaleValidator(); + $validator->validate(array(), $this->getMockConstraint()); + } + public function testValidateEmptyLocale() + { + $validator = new LocaleValidator(); + $validator->validate(null, $this->getMockConstraint()); + $validator->validate('', $this->getMockConstraint()); } /** @@ -166,4 +184,9 @@ private function getLocaleValidator($intlExtension = false) return $validator; } + + protected function getMockConstraint() + { + return $this->getMock('Symfony\Component\Validator\Constraint'); + } } diff --git a/Twig/Extension/LocaleSwitcherExtension.php b/Twig/Extension/LocaleSwitcherExtension.php index c10e4ee..cc17147 100644 --- a/Twig/Extension/LocaleSwitcherExtension.php +++ b/Twig/Extension/LocaleSwitcherExtension.php @@ -54,8 +54,11 @@ public function getName() } /** - * @param string $route A route name for which the switch has to be made - * @param array $parameters + * @param string $route A route name for which the switch has to be made + * @param array $parameters + * @param string $template + * + * @return mixed */ public function renderSwitcher($route = null, $parameters = array(), $template = null) { diff --git a/Validator/LocaleAllowedValidator.php b/Validator/LocaleAllowedValidator.php index 50d8ddc..fa5c9fd 100644 --- a/Validator/LocaleAllowedValidator.php +++ b/Validator/LocaleAllowedValidator.php @@ -41,7 +41,7 @@ class LocaleAllowedValidator extends ConstraintValidator * * @param array $allowedLocales List of allowed locales * @param bool $strictMode Match locales strict (e.g. de_DE will not match allowedLocale de) - * @param bool $intlExtension Wether the intl extension is installed + * @param bool $intlExtension Whether the intl extension is installed */ public function __construct(array $allowedLocales = array(), $strictMode = false, $intlExtension = false) {