/**
* Callback method that listens to the `beforeFind` event in the bound
* table. It modifies the passed query by eager loading the translated fields
* and adding a formatter to copy the values into the main table records.
*
* @param \Cake\Event\Event $event The beforeFind event that was fired.
* @param \Cake\ORM\Query $query Query
* @param \ArrayObject $options The options for the query
* @return void
*/
public function beforeFind(Event $event, Query $query, $options)
{
$locale = $this->locale();
if ($locale === $this->config('defaultLocale')) {
return;
}
$conditions = function ($field, $locale, $query, $select) {
return function ($q) use($field, $locale, $query, $select) {
$q->where([$q->repository()->aliasField('locale') => $locale]);
if ($query->autoFields() || in_array($field, $select, true) || in_array($this->_table->aliasField($field), $select, true)) {
$q->select(['id', 'content']);
}
return $q;
};
};
$contain = [];
$fields = $this->_config['fields'];
$alias = $this->_table->alias();
$select = $query->clause('select');
$changeFilter = isset($options['filterByCurrentLocale']) && $options['filterByCurrentLocale'] !== $this->_config['onlyTranslated'];
foreach ($fields as $field) {
$name = $alias . '_' . $field . '_translation';
$contain[$name]['queryBuilder'] = $conditions($field, $locale, $query, $select);
if ($changeFilter) {
$filter = $options['filterByCurrentLocale'] ? 'INNER' : 'LEFT';
$contain[$name]['joinType'] = $filter;
}
}
$query->contain($contain);
$query->formatResults(function ($results) use($locale) {
return $this->_rowMapper($results, $locale);
}, $query::PREPEND);
}