Skip to content

Instantly share code, notes, and snippets.

@Taluu
Created October 23, 2013 11:13
Show Gist options
  • Select an option

  • Save Taluu/7116759 to your computer and use it in GitHub Desktop.

Select an option

Save Taluu/7116759 to your computer and use it in GitHub Desktop.
<?php
class DoctrineItemSummaryListener implements EventSubscriber
{
/** @var TagcloudGenerator */
private $tagcloud;
public function __construct(TagcloudGenerator $tagcloud)
{
$this->tagcloud = $tagcloud;
}
public function getSubscribedEvents() {
return ['prePersist', 'preUpdate'];
}
public function prePersist(LifecycleEventArgs $event)
{
$entity = $event->getEntity();
if (!$entity instanceof Item) {
return;
}
$entity->setSummary($entity->computeSummary());
}
public function preUpdate(PreUpdateEventArgs $event)
{
$entity = $event->getEntity();
if (!$entity instanceof Item) {
return;
}
$summary = $entity->computeSummary();
// special treatment for Text type
if ($entity instanceof Text) {
$summary = [];
$answers = $entity->getAnswers()->map(function (ItemAnswer $answer) { return $answer->getValue(); })->getValues();
foreach (json_decode($this->tagcloud->getTagcloudFromArray('survey.item', $entity->getId(), $answers, true)) ?: [] as $tuple) {
$summary[$tuple[0]] = $tuple[1];
}
}
// now alter the current options value
$options = $entity->getOptions();
$options['cached'] = ['summary' => $summary];
$event->setNewValue('options', $options);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment