Skip to content

Commit

Permalink
Merge pull request #49 from SahAssar/master
Browse files Browse the repository at this point in the history
Fix #47, #46 and #41 among other small issues
  • Loading branch information
SahAssar authored Jul 27, 2016
2 parents 2a27521 + 0eebecc commit 2fcdda0
Show file tree
Hide file tree
Showing 8 changed files with 118 additions and 56 deletions.
12 changes: 9 additions & 3 deletions config/config.yml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,25 @@ locales:
label: Deutsch
slug: de

# Enable/disable automatic routing.
# Enable/disable automatic routing override.
# Enabling this will prefix all routes with {_locale} which leads to links like
# /en/pages/yourpageslug It is reccomended that you leave this on unless you
# want to build your own routing.
routing_override: true

# Enable/disable the menubuilder.
# Enable/disable the menubuilder override.
# Enabling this will make the menu output links in the format of the automatic
# routing. It is reccomended that you leave this on unless you want to build
# your own localized menus.
menu_override: true

# Enable/disable the url_generator override.
# Enabling this will override the url generator to make sure that we don't
# generate links without a locale. This is highlig reccomended to keep unless
# you also build your own override since it can cause WSOD on 404's otherwise.
url_generator_override: true

# Enable/disable translated slugs.
# Enabling this will use translated slugs instead of using the same slug for
# all languages. Only set to false if you also don't set your slugs to `is_translateable`.
translate_slugs: true
translate_slugs: true
16 changes: 16 additions & 0 deletions src/Config/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,4 +110,20 @@ public function setTranslateSlugs($translateSlugs)
{
$this->set('translate_slugs', $translateSlugs);
}

/**
* @return boolean
*/
public function isUrlGeneratorOverride()
{
return $this->get('url_generator_override', true);
}

/**
* @param boolean $urlGeneratorOverride
*/
public function setUrlGeneratorOverride($urlGeneratorOverride)
{
$this->set('url_generator_override', $urlGeneratorOverride);
}
}
48 changes: 32 additions & 16 deletions src/EventListener/StorageListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,6 @@
*/
class StorageListener implements EventSubscriberInterface
{
/** @var string */
protected $localeSlug;

/** @var BoltConfig */
private $boltConfig;
/** @var Query $query */
Expand Down Expand Up @@ -82,19 +79,21 @@ public function preHydrate(HydrationEvent $event)
return;
}

$localeSlug = $request->get('_locale');

/** @var Content $entity */
$entity = $event->getArgument('entity');
$subject = $event->getSubject();

if (!$entity instanceof Content || $request->query->getBoolean('no_locale_hydrate')) {
if (!$entity instanceof Content || $request->request->getBoolean('no_locale_hydrate')) {
return;
}

$contentTypeName = $entity->getContenttype();
$contentType = $this->boltConfig->get('contenttypes/' . $contentTypeName);

if (isset($subject[$this->localeSlug . '_data'])) {
$localeData = json_decode($subject[$this->localeSlug . '_data'], true);
if (isset($subject[$localeSlug . '_data'])) {
$localeData = json_decode($subject[$localeSlug . '_data'], true);
foreach ($localeData as $key => $value) {
if ($contentType['fields'][$key]['type'] !== 'repeater') {
$subject[$key] = is_array($value) ? json_encode($value) : $value;
Expand All @@ -115,19 +114,21 @@ public function postHydrate(HydrationEvent $event)
return;
}

$localeSlug = $request->get('_locale');

/** @var Content $subject */
$subject = $event->getSubject();
if (!$subject instanceof Content || $request->query->getBoolean('no_locale_hydrate')) {
if (!$subject instanceof Content || $request->request->getBoolean('no_locale_hydrate')) {
return;
}

$contentTypeName = $subject->getContenttype();
$contentType = $this->boltConfig->get('contenttypes/' . $contentTypeName);

if (!isset($subject[$this->localeSlug . '_data'])) {
if (!isset($subject[$localeSlug . '_data'])) {
return;
}
$localeData = json_decode($subject[$this->localeSlug . '_data'], true);
$localeData = json_decode($subject[$localeSlug . '_data'], true);
foreach ($localeData as $key => $value) {
if ($contentType['fields'][$key]['type'] !== 'repeater') {
continue;
Expand All @@ -147,6 +148,11 @@ public function postHydrate(HydrationEvent $event)
*/
public function preSave(StorageEvent $event)
{
$request = $this->requestStack->getCurrentRequest();
if ($request === null) {
return;
}

$contentType = $this->boltConfig->get('contenttypes/' . $event->getContentType());
$translatableFields = $this->getTranslatableFields($contentType['fields']);
/** @var Content $record */
Expand All @@ -158,10 +164,11 @@ public function preSave(StorageEvent $event)
return;
}

$record->set($this->localeSlug . '_slug', $values['slug']);
if ($values['locale'] == key($this->config->getLocales())) {
$record->set($this->localeSlug . '_data', '[]');
$localeSlug = $request->get('_locale');

$record->set($localeSlug . '_slug', $values['slug']);
if ($values['_locale'] == reset($this->config->getLocales())->getSlug()) {
$record->set($localeSlug . '_data', '[]');
return;
}

Expand All @@ -181,7 +188,7 @@ public function preSave(StorageEvent $event)
}
}
$localeJson = json_encode($localeValues);
$record->set($this->localeSlug . '_data', $localeJson);
$record->set($localeSlug . '_data', $localeJson);
}

/**
Expand All @@ -191,15 +198,22 @@ public function preSave(StorageEvent $event)
*/
public function postSave(StorageEvent $event)
{
$request = $this->requestStack->getCurrentRequest();
if ($request === null) {
return;
}

$localeSlug = $request->get('_locale');
$subject = $event->getSubject();

if (!$subject instanceof Content) {
return;
}
if (isset($subject[$this->localeSlug . '_data'])) {
if (!isset($subject[$localeSlug . '_data'])) {
return;
}

$localeData = json_decode($subject[$this->localeSlug . '_data']);
$localeData = json_decode($subject[$localeSlug . '_data']);
foreach ($localeData as $key => $value) {
$subject->set($key, $value);
}
Expand All @@ -216,7 +230,9 @@ private function getTranslatableFields($fields)
{
$translatable = [];
foreach ($fields as $name => $field) {
if (isset($field['is_translateable']) && $field['is_translateable'] === true && $field['type'] === 'templateselect') {
if (isset($field['is_translateable']) &&
$field['is_translateable'] === true &&
$field['type'] === 'templateselect') {
$translatable[] = 'templatefields';
} elseif (isset($field['is_translateable']) && $field['is_translateable'] === true) {
$translatable[] = $name;
Expand Down
16 changes: 14 additions & 2 deletions src/Frontend/LocalizedFrontend.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,25 @@ protected function getConfigurationRoutes()
$routes = $this->app['config']->get('routing', []);

if ($this->app['translate.config']->isRoutingOverride()) {
/** @var Config\Config $config */
$config = $this->app['translate.config'];
foreach ($config->getLocales() as $locale) {
$requirements = $locale->getSlug() . '|' . $requirements;
}

foreach ($routes as $name => &$route) {
if ($name !== 'preview') {
$route['path'] = '/{_locale}' . $route['path'];
$route['requirements']['_locale'] = '^[a-z]{2}(_[A-Z]{2})?$';
$route['requirements']['_locale'] = $requirements;
}
}
$routes['homepageredir'] = ['path' => '/', 'defaults' => [ '_controller' => 'controller.frontend:homepageRedirect' ]];

$routes = array_merge([
'homepageredir' => [
'path' => '/',
'defaults' => ['_controller' => 'controller.frontend:homepageRedirect']
]
], $routes);
}

return $routes;
Expand Down
4 changes: 3 additions & 1 deletion src/Frontend/LocalizedMenuBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ private function resolveRouteToLink(array $item)
private function resolvePathToContent(array $item)
{
if ($item['path'] === 'homepage') {
$item['link'] = $this->app['resources']->getUrl('root') . $this->prefix;
$item['link'] = rtrim($this->app['resources']->getUrl('root') . $this->prefix, '/');

return $item;
}
Expand Down Expand Up @@ -125,6 +125,8 @@ private function resolvePathToContent(array $item)
// Route is probably a GET and we're currently in a POST
}



return $item;
}
private function populateItemFromRecord(array $item, $path)
Expand Down
47 changes: 28 additions & 19 deletions src/TranslateExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,14 @@ public function before(Request $request, Application $app)
protected function subscribe(EventDispatcherInterface $dispatcher)
{
$app = $this->getContainer();
$dispatcher->addSubscriber(new EventListener\StorageListener($app['config'], $app['translate.config'], $app['query'], $app['request_stack']));
$dispatcher->addSubscriber(
new EventListener\StorageListener(
$app['config'],
$app['translate.config'],
$app['query'],
$app['request_stack']
)
);
}

/**
Expand Down Expand Up @@ -114,7 +121,7 @@ function ($app) {
}

foreach ($config->getLocales() as $locale) {
if ($localeSlug == $locale->getSlug()) {
if ($localeSlug === $locale->getSlug()) {
return $localeSlug;
}
}
Expand Down Expand Up @@ -147,23 +154,25 @@ function ($app) {
}
);

$app['url_generator'] = $app->extend(
'url_generator',
function ($urlGenerator) use ($app) {
$requestContext = $urlGenerator->getContext();
if ($app['translate.config']->isUrlGeneratorOverride()) {
$app['url_generator'] = $app->extend(
'url_generator',
function ($urlGenerator) use ($app) {
$requestContext = $urlGenerator->getContext();

if (is_null($requestContext->getParameter('_locale'))) {
$config = $app['translate.config'];
/** @var Config\Locale $locale */
$locale = reset($config->getLocales());
$defaultSlug = $locale->getSlug();
if (is_null($requestContext->getParameter('_locale'))) {
$config = $app['translate.config'];
/** @var Config\Locale $locale */
$locale = reset($config->getLocales());
$defaultSlug = $locale->getSlug();

$requestContext->setParameter('_locale', $defaultSlug);
}
$requestContext->setParameter('_locale', $defaultSlug);
}

return $urlGenerator;
}
);
return $urlGenerator;
}
);
}

if ($app['translate.config']->isMenuOverride()) {
$app['menu'] = $app->share(
Expand Down Expand Up @@ -227,17 +236,17 @@ public function getCurrentLocaleStructure()
/** @var Config\Locale $locale */
foreach ($locales as $iso => $locale) {
$requestAttributes = $request->attributes->get('_route_params');
$requestLocale = isset($requestAttributes['_locale']) ? $requestAttributes['_locale'] : null;
$requestLocale = $request->get('_locale');
if ($config->isTranslateSlugs() && $locale->getSlug() !== $requestLocale && $request->get('slug')) {
$repo = $app['storage']->getRepository('pages');
$qb = $repo->createQueryBuilder();
$qb->select($locale->getSlug() . '_slug')
->where($requestAttributes['_locale'] . '_slug = ?')
->where($locale->getSlug() . '_slug = ?')
->setParameter(0, $request->get('slug'))
;
$newSlug = $repo->findOneWith($qb);
if ($newSlug) {
$requestAttributes['slug'] = $newSlug;
$requestAttributes['slug'] = $newSlug[$locale->getSlug() . '_slug'];
}
}

Expand Down
23 changes: 12 additions & 11 deletions templates/fields/_locale.twig
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
{% set locales = app['translate.config'].locales %}
{% set current = locales|first %}
{% set locales = app['translate.config'].getLocales() %}
{% set currentkey = locales|keys|first %}
{% set current = locales|first %}
{% set translatable = [] %}

{% for name, field in context.contenttype.fields %}
{% if field.is_translateable is defined and field.is_translateable == true %}
{% set translatable = translatable|merge(['#'~name]) %}
{% set translatable = translatable|merge(['[name^="'~name~'[0]"]']) %}
{% endif %}
{% endfor %}

{% for key, option in locales %}
{% set current = option.get('slug') == app.request.get('_locale') ? option.get('slug') : current %}
{% set currentkey = option.get('slug') == app.request.get('_locale') ? key : currentkey %}
{% set current = option.get('slug') == app['translate.slug'] ? option : current %}
{% set currentkey = option.get('slug') == app['translate.slug'] ? key : currentkey %}
{% endfor %}
<input name="locale" type="hidden" value="{{currentkey}}">
<input name="_locale" type="hidden" value="{{current.slug}}">
<input name="_locale" type="hidden" value="{{current.get('slug')}}">
<input name="no_locale_hydrate" type="hidden" value="true">

<fieldset class="locale">
<div class="col-sm-12">
{% if app.request.get('id') is not empty %}
<div class="dropdown pull-right" id="locale-select">
<button class="btn btn-default dropdown-toggle" data-toggle="dropdown" type="button">
<span class="selected">{{ current.label }}</span>
<span class="selected">{{ current.get('label') }}</span>
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
Expand All @@ -43,8 +43,8 @@
<script>
$(function() {
// Prepend translation icons to translatable fields.
$('{{translatable|join(",")}}')
.closest('fieldset')
$('{{translatable|join(",")|raw}}')
.closest('[data-bolt-fieldset]')
.each(function(i, el){
$(el).find('label')
.first()
Expand All @@ -60,19 +60,20 @@
$('#sidebarpreviewbutton')
.attr(
'data-url',
"{{ path('preview', {'contenttypeslug': context.contenttype.singular_slug, _locale: current.slug}) }}"
"{{ path('preview', {'contenttypeslug': context.contenttype.singular_slug, _locale: current.get('slug')}) }}"
);
{% if context.content.slug|default(false) %}
// Fix "view saved" link
$('[href="{{ context.content.link }}"]')
.attr(
'href',
"{{ path('contentlink', {'contenttypeslug': context.contenttype.singular_slug, slug: context.content.slug, _locale: current.slug}) }}"
"{{ path('contentlink', {'contenttypeslug': context.contenttype.singular_slug, slug: context.content.slug, _locale: current.get('slug')}) }}"
);
{% endif %}
});
</script>

<style>
#locale-select button {
border-radius: 4px 4px 0 0;
Expand Down
8 changes: 4 additions & 4 deletions templates/frontend/_localeswitcher.twig
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<ul{% if classes %} class="{{ classes }}"{% endif %}>
{% for iso, locale in locales %}
<li{% if locale.active %} class="active"{% endif %}>
<a title="{{ locale.label }}" href="{{ locale.url }}">
{{ locale.label }}
{% for locale in locales %}
<li{% if locale.get('active') %} class="active"{% endif %}>
<a title="{{ locale.get('label') }}" href="{{ locale.get('url') }}">
{{ locale.get('label') }}
</a>
{% endfor %}
</ul>

0 comments on commit 2fcdda0

Please sign in to comment.