Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Implement ConfigCachingService, update controller and add JS code
  • Loading branch information
Andy Wermke committed Aug 6, 2015
1 parent d0d2068 commit 9f7d361
Show file tree
Hide file tree
Showing 20 changed files with 414 additions and 60 deletions.
18 changes: 15 additions & 3 deletions README.md
Expand Up @@ -67,7 +67,7 @@ return [
'reminder' => [
'password', 'user', 'token'
]
]
],

/*
* in short:
Expand All @@ -82,18 +82,29 @@ return [
* 'reminder.token'
* ]
*/

// Set the keys of config properties you want to use in javascript.
// Caution: Do not expose any configuration values that should be kept privately!
'config' => [
'app.debug'
],

// Disables the config cache if set to true, so you don't have to run `php artisan js-localization:refresh`
// each time you change configuration files.
// Attention: Should not be used in production mode due to decreased performance.
'disable_config_cache' => false,
];
```

__Important:__

The messages configuration will be cached when the JsLocalizationController is used for the first time. After changing the messages configuration you will need to call __`php artisan js-localization:refresh`__ to refresh that cache.
The messages configuration will be cached when the JsLocalizationController is used for the first time. After changing the messages configuration you will need to call __`php artisan js-localization:refresh`__ to refresh that cache. That also affects the config properties you export to javascript, since they are cached, too.


Usage
-----

You just need to add the neccessary `<script>` tags to your layout. Here is an example blade view:
You just need to add the necessary `<script>` tags to your layout. Here is an example blade view:

```html
@include('js-localization::head')
Expand All @@ -118,6 +129,7 @@ Features
--------

You may use Lang.get(), Lang.has(), Lang.choice(), Lang.locale() and trans() (alias for Lang.get()) in your Javascript code. They work just like Laravel's `Lang` facade.
Additionally, you are able to pass configuration properties to your Javascript code as well. There is Config.get() in Javascript, too. Configure which config properties to pass to the client using the `config` field in `config/js-localization.php`. Attention: Do not export any security-critical properties like DB credentials or similar, since they would be visible to anyone using your application!

Variables in messages are supported. For instance: `"This is my test string for :name."`.

Expand Down
19 changes: 19 additions & 0 deletions config/config.php
Expand Up @@ -30,4 +30,23 @@

'messages' => [],

/*
|--------------------------------------------------------------------------
| Set the keys of config properties you want to use in javascript.
| Caution: Do not expose any configuration values that should be kept privately!
|--------------------------------------------------------------------------
*/
'config' => [
'app.debug'
],

/*
|--------------------------------------------------------------------------
| Disables the config cache if set to true, so you don't have to
| run `php artisan js-localization:refresh` each time you change configuration files.
| Attention: Should not be used in production mode due to decreased performance.
|--------------------------------------------------------------------------
*/
'disable_config_cache' => false,

];
4 changes: 3 additions & 1 deletion gulpfile.js
@@ -1,10 +1,12 @@

var gulp = require('gulp');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');

gulp.task('minify', function() {
return gulp.src('resources/js/localization.js')
return gulp.src('resources/js/*.js')
.pipe(concat('public/js/combined.js'))
.pipe(uglify())
.pipe(rename('localization.min.js'))
.pipe(gulp.dest('public/js'));
Expand Down
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -3,6 +3,7 @@
"version": "0.1.0",
"devDependencies": {
"gulp": "^3.9.0",
"gulp-concat": "^2.6.0",
"gulp-rename": "^1.2.2",
"gulp-uglify": "^1.2.0"
}
Expand Down
2 changes: 1 addition & 1 deletion public/js/localization.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

35 changes: 35 additions & 0 deletions resources/js/config.js
@@ -0,0 +1,35 @@
(function() {

var configData = {};


/* Config: */

var Config = {
get: function(propertyName, defaultValue) {
if (typeof configData[propertyName] !== 'undefined') {
return configData[propertyName];
}

// Config property not set

if (arguments.length > 1) {
return defaultValue;
} else {
return null;
}
},

addConfig: function(data) {
for (var propertyName in data) {
configData[propertyName] = data[propertyName];
}
}
};


/* Export: */

this.Config = Config;

})();
37 changes: 32 additions & 5 deletions src/Caching/AbstractCachingService.php
Expand Up @@ -9,6 +9,7 @@
namespace JsLocalization\Caching;

use Cache;
use DateTime;

abstract class AbstractCachingService {

Expand Down Expand Up @@ -39,25 +40,51 @@ public function __construct($cacheKey, $cacheTimestampKey)
}

/**
* Returns the UNIX timestamp of the last
* refreshCache() call.
* Returns the timestamp of the last refreshCache() call.
*
* @return int UNIX timestamp
* @return DateTime
*/
public function getLastRefreshTimestamp()
{
return Cache::get($this->cacheTimestampKey);
$unixTime = Cache::get($this->cacheTimestampKey);

$dateTime = new DateTime;
$dateTime->setTimestamp($unixTime);

return $dateTime;
}

/**
* Refresh the cached data.
*
* @param mixed $data
*/
public function refreshCache($data)
public function refreshCacheUsing($data)
{
Cache::forever($this->cacheKey, $data);
Cache::forever($this->cacheTimestampKey, time());
}

/**
* Create up-to-date data and update cache using refreshCacheUsing().
* Trigger some event.
*
* @return void
*/
abstract public function refreshCache();

/**
* Return the cached data. Refresh cache if cache has not yet been initialized.
*
* @return mixed
*/
public function getData()
{
if (!Cache::has($this->cacheKey)) {
$this->refreshCache();
}

return Cache::get($this->cacheKey);
}

}
67 changes: 61 additions & 6 deletions src/Caching/ConfigCachingService.php
@@ -1,14 +1,69 @@
<?php
namespace JsLocalization\Caching;

use Config;
use Event;

/**
* Created by PhpStorm.
* User: andy
* Date: 03.08.15
* Time: 00:11
* Class ConfigCachingService
* @package JsLocalization\Caching
*/
class ConfigCachingService extends AbstractCachingService {

namespace JsLocalization\Caching;
const CACHE_KEY = 'js-localization-config-json';

const CACHE_TIMESTAMP_KEY = 'js-localization-config-last-modified';

class ConfigCachingService extends AbstractCachingService {

public function __construct()
{
parent::__construct(self::CACHE_KEY, self::CACHE_TIMESTAMP_KEY);
}

/**
* @return void
*/
public function refreshCache()
{
Event::fire('JsLocalization.registerConfig');

$configJson = $this->createConfigJson();
$this->refreshCacheUsing($configJson);
}

/**
* @return string The JSON-encoded config exports.
*/
public function getConfigJson()
{
if ($this->isDisabled()) {
return $this->createConfigJson();
} else {
return $this->getData();
}
}

/**
* @return bool Is config caching disabled? `true` means that this class does not cache, but create the data on the fly.
*/
public function isDisabled()
{
return Config::get('js-localization.disable_config_cache', false);
}

/**
* @return string
*/
protected function createConfigJson()
{
$propertyNames = Config::get('js-localization.config', []);
$configArray = [];

foreach ($propertyNames as $propertyName) {
$configArray[$propertyName] = Config::get($propertyName);
}

return json_encode((object)$configArray);
}

}
10 changes: 3 additions & 7 deletions src/Caching/MessageCachingService.php
Expand Up @@ -23,7 +23,7 @@ class MessageCachingService extends AbstractCachingService
*
* @var string
*/
const CACHE_TIMESTAMP_KEY = 'js-localization-last-modified';
const CACHE_TIMESTAMP_KEY = 'js-localization-messages-last-modified';


public function __construct()
Expand All @@ -39,11 +39,7 @@ public function __construct()
*/
public function getMessagesJson()
{
if (!Cache::has($this->cacheKey)) {
$this->refreshCache();
}

return Cache::get($this->cacheKey);
return $this->getData();
}

/**
Expand All @@ -61,7 +57,7 @@ public function refreshCache()
$messageKeys = $this->getMessageKeys();
$translatedMessages = $this->getTranslatedMessagesForLocales($messageKeys, $locales);

parent::refreshCache(json_encode($translatedMessages));
$this->refreshCacheUsing(json_encode($translatedMessages));
}

/**
Expand Down
2 changes: 2 additions & 0 deletions src/Console/RefreshCommand.php
Expand Up @@ -4,6 +4,7 @@
use Config;
use Illuminate\Console\Command;
use JsLocalization\Exceptions\ConfigException;
use JsLocalization\Facades\ConfigCachingService;
use JsLocalization\Facades\MessageCachingService;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
Expand Down Expand Up @@ -42,6 +43,7 @@ public function fire()
}

MessageCachingService::refreshCache();
ConfigCachingService::refreshCache();
}

}
28 changes: 28 additions & 0 deletions src/Facades/ConfigCachingService.php
@@ -0,0 +1,28 @@
<?php
/**
* Created by PhpStorm.
* User: andy
* Date: 03.08.15
* Time: 16:40
*/

namespace JsLocalization\Facades;


use Illuminate\Support\Facades\Facade;

/**
* Class ConfigCachingService
* @package JsLocalization\Facades
*
* @method static void refreshCache()
* @method static \DateTime getLastRefreshTimestamp()
* @method static string getConfigJson()
* @method static bool isDisabled()
* @method static void public function refreshCache()
*/
class ConfigCachingService extends Facade {
protected static function getFacadeAccessor() {
return 'JsLocalizationConfigCachingService';
}
}
2 changes: 1 addition & 1 deletion src/Facades/MessageCachingService.php
Expand Up @@ -8,7 +8,7 @@
* @package JsLocalization\Facades
*
* @method static void refreshCache()
* @method static int getLastRefreshTimestamp()
* @method static \DateTime getLastRefreshTimestamp()
* @method static string getMessagesJson()
* @method static void public function refreshCache()
*/
Expand Down

0 comments on commit 9f7d361

Please sign in to comment.