Skip to content

Commit

Permalink
Merge pull request #36 from creative-commoners/pulls/2.0/allow-errors…
Browse files Browse the repository at this point in the history
…-as-ok

FIX Allow errors to be returned as OK, and default language to the first locale
  • Loading branch information
NightJar authored May 4, 2018
2 parents 434e3d6 + a3b586a commit b1e662a
Show file tree
Hide file tree
Showing 5 changed files with 106 additions and 24 deletions.
2 changes: 1 addition & 1 deletion lang/en.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
en:
SilverStripe\SpellCheck\Handling\SpellController:
InvalidLocale: 'Not supported locale'
InvalidLocale: 'Not a supported locale'
InvalidRequest: 'Invalid request'
MissingData: 'Could not get raw post data'
MissingProviders: 'No spellcheck module installed'
Expand Down
46 changes: 38 additions & 8 deletions src/Handling/SpellCheckMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use SilverStripe\Control\Middleware\HTTPMiddleware;
use SilverStripe\Core\Config\Configurable;
use SilverStripe\Forms\HTMLEditor\HTMLEditorConfig;
use SilverStripe\Forms\HTMLEditor\TinyMCEConfig;
use SilverStripe\i18n\i18n;
use SilverStripe\Security\SecurityToken;

Expand All @@ -25,17 +26,25 @@ class SpellCheckMiddleware implements HTTPMiddleware
public function process(HTTPRequest $request, callable $delegate)
{
// Set settings
$editor = static::config()->get('editor');
HTMLEditorConfig::get($editor)->enablePlugins('spellchecker');
HTMLEditorConfig::get($editor)->addButtonsToLine(2, 'spellchecker');
$editor = $this->config()->get('editor');

/** @var TinyMCEConfig $editorConfig */
$editorConfig = TinyMCEConfig::get($editor);

$editorConfig->enablePlugins('spellchecker');
$editorConfig->addButtonsToLine(2, 'spellchecker');

$token = SecurityToken::inst();
HTMLEditorConfig::get($editor)

$editorConfig
->setOption('spellchecker_rpc_url', Director::absoluteURL($token->addToUrl('spellcheck/')))
->setOption('browser_spellcheck', false)
->setOption(
'spellchecker_languages',
implode(',', $this->getLanguages())
);
->setOption('spellchecker_languages', implode(',', $this->getLanguages()));

$defaultLocale = $this->getDefaultLocale();
if ($defaultLocale) {
$editorConfig->setOption('spellchecker_language', $defaultLocale);
}

return $delegate($request);
}
Expand All @@ -53,4 +62,25 @@ public function getLanguages()
}
return $languages;
}

/**
* Returns the default locale for TinyMCE. Either via configuration or the first in the list of locales.
*
* @return string|false
*/
public function getDefaultLocale()
{
// Check configuration first
$defaultLocale = SpellController::config()->get('default_locale');
if ($defaultLocale) {
return $defaultLocale;
}

// Grab the first one in the list
$locales = SpellController::get_locales();
if (empty($locales)) {
return false;
}
return reset($locales);
}
}
34 changes: 26 additions & 8 deletions src/Handling/SpellController.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,16 @@ class SpellController extends Controller
* @var array
* @config
*/
private static $locales = array();
private static $locales = [];

/**
* Optional: define the default locale for TinyMCE instances. If not defined, the first locale in the list of
* available locales will be used.
*
* @var string|bool
* @config
*/
private static $default_locale = false;

/**
* Necessary permission required to spellcheck. Set to empty or null to disable restrictions.
Expand All @@ -39,6 +48,14 @@ class SpellController extends Controller
*/
private static $enable_security_token = true;

/**
* If true, all error messages will be returned with a 200 OK HTTP header code
*
* @var bool
* @config
*/
private static $return_errors_as_ok = false;

/**
* Dependencies required by this controller
*
Expand Down Expand Up @@ -81,7 +98,7 @@ public function getProvider()
public static function get_locales()
{
// Default to current locale if none configured
return self::config()->locales ?: array(i18n::get_locale());
return self::config()->get('locales') ?: array(i18n::get_locale());
}

/**
Expand Down Expand Up @@ -116,18 +133,19 @@ protected function success($result)
}

/**
* Set the error
* Set the error.
*
* @param string $message
* @param int $code HTTP error code
*/
protected function error($message, $code)
{
$error = [
'error' => $message,
];
// Some clients may require errors to be returned with a 200 OK header code
if ($this->config()->get('return_errors_as_ok')) {
$code = 200;
}

return $this->result($error, $code);
return $this->result(['error' => $message], $code);
}

public function index()
Expand Down Expand Up @@ -167,7 +185,7 @@ public function index()
// Check locale
$locale = $this->getLocale($data);
if (!$locale) {
return $this->error(_t(__CLASS__ . '.InvalidLocale', 'Not supported locale'), 400);
return $this->error(_t(__CLASS__ . '.InvalidLocale', 'Not a supported locale'), 400);
}

// Check provider
Expand Down
24 changes: 24 additions & 0 deletions tests/Handling/SpellCheckMiddlewareTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

namespace SilverStripe\Spellcheck\Tests\Handling;

use SilverStripe\Core\Config\Config;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\SpellCheck\Handling\SpellCheckMiddleware;
use SilverStripe\SpellCheck\Handling\SpellController;

class SpellCheckMiddlewareTest extends SapphireTest
{
public function testGetDefaultLocale()
{
$middleware = new SpellCheckMiddleware();

Config::modify()->set(SpellController::class, 'default_locale', 'foo');
$this->assertSame('foo', $middleware->getDefaultLocale(), 'Returns configured default');

Config::modify()
->set(SpellController::class, 'default_locale', false)
->set(SpellController::class, 'locales', ['foo_BAR', 'bar_BAZ']);
$this->assertSame('foo_BAR', $middleware->getDefaultLocale(), 'Returns first in `locales`');
}
}
24 changes: 17 additions & 7 deletions tests/SpellControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,11 @@ protected function setUp()
// Reset config
Config::modify()->set(SpellController::class, 'required_permission', 'CMS_ACCESS_CMSMain');
Config::inst()->remove(SpellController::class, 'locales');
Config::modify()->set(SpellController::class, 'locales', array('en_US', 'en_NZ', 'fr_FR'));
Config::modify()->set(SpellController::class, 'enable_security_token', true);
Config::modify()
->set(SpellController::class, 'locales', array('en_US', 'en_NZ', 'fr_FR'))
->set(SpellController::class, 'enable_security_token', true)
->set(SpellController::class, 'return_errors_as_ok', false);

SecurityToken::enable();

// Setup mock for testing provider
Expand Down Expand Up @@ -123,10 +126,12 @@ public function testPermissions()
* @param int $expectedStatusCode
* @dataProvider langProvider
*/
public function testBothLangAndLocaleInputResolveToLocale($lang, $expectedStatusCode)
public function testBothLangAndLocaleInputResolveToLocale($lang, $expectedStatusCode, $errorsAreOk = false)
{
$this->logInWithPermission('ADMIN');
Config::modify()->set(SpellController::class, 'enable_security_token', false);
Config::modify()
->set(SpellController::class, 'enable_security_token', false)
->set(SpellController::class, 'return_errors_as_ok', $errorsAreOk);

$mockData = [
'ajax' => true,
Expand Down Expand Up @@ -156,6 +161,11 @@ public function langProvider()
'ru',
400,
],
'invalid_language_returned_as_ok' => [
'ru',
200,
true
],
'other_valid_language' => [
'fr', // assumes fr_FR is the default locale for "en" language
200,
Expand Down Expand Up @@ -204,7 +214,7 @@ public function testInputRejection()
$jsonBody = json_decode($response->getBody());
$this->assertEquals(
_t(
'SilverStripe\\SpellCheck\\Handling\\.UnsupportedMethod',
'SilverStripe\\SpellCheck\\Handling\\SpellController.UnsupportedMethod',
"Unsupported method '{method}'",
array('method' => 'validate')
),
Expand All @@ -227,8 +237,8 @@ public function testInputRejection()
$this->assertEquals(400, $response->getStatusCode());
$jsonBody = json_decode($response->getBody());
$this->assertEquals(_t(
'SilverStripe\\SpellCheck\\Handling\\.InvalidLocale',
'Not supported locale'
'SilverStripe\\SpellCheck\\Handling\\SpellController.InvalidLocale',
'Not a supported locale'
), $jsonBody->error);
}
}

0 comments on commit b1e662a

Please sign in to comment.