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

GitHub 144 localizable custom entities #148

Open
wants to merge 5 commits into
base: master
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ vendor
composer.phar
composer.lock
docker-compose.yml
.idea/
52 changes: 46 additions & 6 deletions Connector/Processor/Denormalization/ReferenceDataProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Akeneo\Component\StorageUtils\Detacher\ObjectDetacherInterface;
use Akeneo\Component\StorageUtils\Updater\ObjectUpdaterInterface;
use Doctrine\ORM\EntityManagerInterface;
use Pim\Bundle\CatalogBundle\Doctrine\ORM\Repository\LocaleRepository;
use Pim\Bundle\CustomEntityBundle\Configuration\Registry;
use Pim\Bundle\CustomEntityBundle\Entity\Repository\CustomEntityRepository;
use Pim\Component\Connector\Exception\InvalidItemFromViolationsException;
Expand Down Expand Up @@ -44,25 +45,32 @@ class ReferenceDataProcessor implements ItemProcessorInterface, StepExecutionAwa
/** @var StepExecution */
protected $stepExecution;

/** @var LocaleRepository */
protected $localeRepository;

/**
* ReferenceDataProcessor constructor.
* @param Registry $confRegistry
* @param EntityManagerInterface $em
* @param ObjectUpdaterInterface $updater
* @param ValidatorInterface $validator
* @param ObjectDetacherInterface $detacher
* @param LocaleRepository $localeRepository
*/
public function __construct(
Registry $confRegistry,
EntityManagerInterface $em,
ObjectUpdaterInterface $updater,
ValidatorInterface $validator,
ObjectDetacherInterface $detacher
ObjectDetacherInterface $detacher,
LocaleRepository $localeRepository
) {
$this->confRegistry = $confRegistry;
$this->em = $em;
$this->updater = $updater;
$this->validator = $validator;
$this->detacher = $detacher;
$this->confRegistry = $confRegistry;
$this->em = $em;
$this->updater = $updater;
$this->validator = $validator;
$this->detacher = $detacher;
$this->localeRepository = $localeRepository;
}

/**
Expand All @@ -75,6 +83,11 @@ public function process($item)
}

$entity = $this->findOrCreateObject($item);

if ($entity instanceof \Pim\Bundle\CustomEntityBundle\Entity\AbstractTranslatableCustomEntity) {
$item = $this->denormalizeTranslations($item);
}

try {
$this->updater->update($entity, $item);
} catch (\Exception $e) {
Expand All @@ -90,6 +103,33 @@ public function process($item)
return $entity;
}

/**
* @param array $item
* @return array
*/
protected function denormalizeTranslations(array $item):array
{
$activatedLocales = $this->localeRepository->getActivatedLocaleCodes();

foreach ($item as $key => $value) {
foreach ($activatedLocales as $localeCode) {
if (preg_match('/.*-(' . preg_quote($localeCode) . ')$/', $key, $match) === 1) {
$attributeCode = str_replace('-' . $localeCode, '', $key);

$item[$attributeCode] = $item[$attributeCode] ?? [];

if (!empty($value)) {
$item[$attributeCode][$localeCode] = $value;
}

unset($item[$key]);
}
}
}

return $item;
}

/**
* {@inheritdoc}
*/
Expand Down
36 changes: 30 additions & 6 deletions Connector/Processor/Normalization/ReferenceDataProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,15 @@ class ReferenceDataProcessor implements ItemProcessorInterface
protected $normalizer;

/** @var string[] */
protected $skippedFields = ['id', 'created', 'updated'];
protected $skippedFields = ['id', 'created', 'updated', 'locale'];

/**
* @param PropertyAccessorInterface $propertyAccessor
* @param NormalizerInterface $normalizer
*/
public function __construct(PropertyAccessorInterface $propertyAccessor, NormalizerInterface $normalizer)
{
public function __construct(PropertyAccessorInterface $propertyAccessor, NormalizerInterface $normalizer) {
$this->propertyAccessor = $propertyAccessor;
$this->normalizer = $normalizer;
$this->normalizer = $normalizer;
}

/**
Expand All @@ -48,13 +47,38 @@ public function process($item)
continue;
}

$value = $this->propertyAccessor->getValue($item, $property->getName());
$normalizedData[$property->getName()] = $this->normalizer->normalize($value, 'flat');
$value = $this->normalizer

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug :
provokes an error
An error occurred during the export execution.

> Error #0 in class Doctrine\Common\Persistence\Mapping\MappingException: The class 'Doctrine\ORM\PersistentCollection' was not found in the chain configured name
> spaces Gedmo\Tree\Entity, Oro\Bundle\ConfigBundle\Entity, Oro\Bundle\UserBundle\Entity, Pim\Bundle\CustomEntityBundle\Entity, FOS\OAuthServerBundle\Entity, Pim\
> Bundle\UserBundle\Entity, Pim\Bundle\ApiBundle\Entity, Pim\Bundle\CatalogBundle\Entity, Pim\Bundle\CommentBundle\Entity, Pim\Bundle\DataGridBundle\Entity, Pim\B
> undle\NotificationBundle\Entity, Amepim\Bundle\CatalogBundle\Entity, Amepim\Bundle\CustomEntityBundle\Entity, Amepim\Bundle\DeletedEntityBundle\Entity, Akeneo\C
> omponent\Batch\Model, Akeneo\Component\BatchQueue\Queue, Akeneo\Component\FileStorage\Model, Pim\Component\Catalog\Model, Akeneo\Component\Versioning\Model

->normalize($this->propertyAccessor->getValue($item, $property->getName()), 'flat');

if (is_array($value)) {
$normalizedData = array_merge($normalizedData, $this->normalizeArray($value));
} else {
$normalizedData[$property->getName()] = $value;
}
}

return $normalizedData;
}

/**
* @param array $values
* @return array
*/
protected function normalizeArray(array $values): array
{
$returnValue = [];

foreach ($values as $key => $value) {
if (is_array($value)) {
$returnValue = array_merge($returnValue, $this->normalizeArray($value));
} else {
$returnValue[$key] = $value;
}
}

return $returnValue;
}

/**
* @param array $skippedFields
*/
Expand Down
1 change: 1 addition & 0 deletions Resources/config/connectors.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ services:
- '@pim_custom_entity.updater.custom_entity'
- '@validator'
- '@akeneo_storage_utils.doctrine.object_detacher'
- '@pim_catalog.repository.locale'

pim_custom_entity.processor.normalization.reference_data:
class: '%pim_custom_entity.processor.normalization.reference_data.class%'
Expand Down
5 changes: 5 additions & 0 deletions Resources/config/requirejs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ config:
custom_entity/controller/edit: pimcustomentity/js/controller/custom_entity-edit
custom_entity/fetcher: pimcustomentity/js/fetcher/custom_entity-fetcher
custom_entity/remover/reference-data: pimcustomentity/js/remover/reference-data-remover
custom_entity/form/localizable/switcher: pimcustomentity/js/form/localizable/switcher
custom_entity/form/localizable/text: pimcustomentity/js/form/localizable/text
custom_entity/form/localizable/textarea: pimcustomentity/js/form/localizable/textarea
custom_entity/template/localizable/text: pimcustomentity/templates/form/localizable/text.html
custom_entity/template/localizable/textarea: pimcustomentity/templates/form/localizable/textarea.html

config:
pim/fetcher-registry:
Expand Down
65 changes: 65 additions & 0 deletions Resources/public/js/form/localizable/switcher.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
define([
'pim/product-edit-form/locale-switcher',
'underscore',
'pim/i18n',
'oro/translator',
'pim/user-context',
], function (LocalSwitcher, _, i18n, __, UserContext) {
"use strict";

return LocalSwitcher.extend({
currentLocaleCode: null,

/**
* {@inheritdoc}
*/
configure: function () {
this.update(UserContext.get('uiLocale'));
},

/**
* Method triggered on the 'change locale' event
*
* @param {Object} event
*/
changeLocale: function (event) {
this.update(event.target.dataset.locale);
},

/**
* @param {String} localeCode
*/
update: function(localeCode) {
this.currentLocaleCode = localeCode;
this.getRoot().trigger('custom_entity:form:custom:translatable:switcher:change', {localeCode: localeCode});
this.render();
},

/**
* {@inheritdoc}
*/
render: function () {
this.getDisplayedLocales()
.done(function (locales) {

if (!this.currentLocaleCode) {
this.currentLocaleCode = _.first(locales).code;
}

this.$el.html(
this.template({
locales: locales,
currentLocale: _.findWhere(locales, {code: this.currentLocaleCode}),
i18n: i18n,
displayInline: this.displayInline,
displayLabel: this.displayLabel,
label: __('pim_enrich.entity.product.meta.locale')
})
);
this.delegateEvents();
}.bind(this));

return this;
},
});
});
95 changes: 95 additions & 0 deletions Resources/public/js/form/localizable/text.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
define([
'pim/common/properties/translation',
'custom_entity/template/localizable/text',
'pim/form',
'underscore',
'jquery',
'pim/user-context',
'oro/translator',
], function (Translation, template, BaseForm, _, $, UserContext, __) {
"use strict";

return Translation.extend({
template: _.template(template),
localeCode: null,

/**
* {@inheritdoc}
*/
configure: function () {
this.listenTo(
this.getRoot(),
'pim_enrich:form:entity:pre_save',
this.onPreSave
);

this.listenTo(
this.getRoot(),
'pim_enrich:form:entity:bad_request',
this.onValidationError
);

this.listenTo(
this.getRoot(),
'pim_enrich:form:entity:locales_updated',
this.onLocalesUpdated.bind(this)
);

this.listenTo(
this.getRoot(),
'custom_entity:form:custom:translatable:switcher:change',
this.onLocaleChanged.bind(this)
);

return $.when(
this.getLocales(true)
.then(function (locales) {
this.locales = locales;
this.localeCode = UserContext.get('uiLocale');
}.bind(this)),
BaseForm.prototype.configure.apply(this, arguments)
);
},

/**
* {@inheritdoc}
*/
render: function () {
this.$el.html(this.template({
model: this.getFormData(),
locales: this.locales,
currentLocaleCode: this.localeCode,
errors: this.validationErrors,
label: __(this.config.label),
fieldName: this.config.fieldName,
isReadOnly: this.isReadOnly()
}));

this.delegateEvents();
this.renderExtensions();
},

/**
* @param {{}} context
*/
onLocaleChanged: function (context) {
this.localeCode = context.localeCode;
this.render();
},

/**
* @param {Object} event
*/
updateModel: function (event) {
var data = this.getFormData();

if (Array.isArray(data[this.config.fieldName])) {
data[this.config.fieldName] = {};
}

data[this.config.fieldName][event.target.dataset.locale] = event.target.value;

this.setData(data);
},
});
});
10 changes: 10 additions & 0 deletions Resources/public/js/form/localizable/textarea.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
define([
'custom_entity/form/localizable/text',
'custom_entity/template/localizable/textarea'
], function (Text, template) {
"use strict";

return Text.extend({
template: _.template(template)
});
});
41 changes: 41 additions & 0 deletions Resources/public/templates/form/localizable/text.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<% _.each(locales, function (locale) { %>
<% if (currentLocaleCode === locale.code) { %>
<div class="AknFieldContainer">
<div class="AknFieldContainer-header">
<label class="AknFieldContainer-label" for="<%- fieldName %><%- locale.code %>">
<%= label %>
</label>
<% var langCode = locale.code.split('_')[1].toLowerCase() %>
<span class="AknFieldContainer-fieldInfo field-info">
<span class="field-context">
<span>
<span class="flag-language">
<i class="flag flag-<%- langCode %>"></i>
<span class="language"><%- langCode %></span>
</span>
</span>
</span>
</span>
</div>
<div class="AknFieldContainer-inputContainer field-input">
<div class="AknTextField-layer AknTextField-layer--first"></div>
<div class="AknTextField-layer AknTextField-layer--second"></div>
<input id="<%- fieldName %><%- locale.code %>"
class="AknTextField AknTextField--localizable label-field"
type="text"
data-locale="<%- locale.code %>"
value="<%- model[fieldName][locale.code] %>"
<%- isReadOnly ? 'readonly disabled' : '' %>
>
</div>
<% if (errors[locale.code]) { %>
<div class="AknFieldContainer-footer">
<span class="validation-error">
<i class="icon-warning-sign"></i>
<span class="error-message"><%- errors[locale.code].message %></span>
</span>
</div>
<% } %>
</div>
<% } %>
<% }) %>
Loading