first impl for global timeline: apply on activities

This commit is contained in:
2021-05-14 16:25:56 +02:00
parent 8c98f2cf6e
commit c3ef8d112c
18 changed files with 604 additions and 98 deletions

View File

@@ -0,0 +1,91 @@
<?php
/*
* Copyright (C) 2015 Champs-Libres Coopérative <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\MainBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Chill\MainBundle\Timeline\TimelineBuilder;
use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
class TimelineCenterController extends AbstractController
{
protected TimelineBuilder $timelineBuilder;
protected PaginatorFactory $paginatorFactory;
private Security $security;
public function __construct(
TimelineBuilder $timelineBuilder,
PaginatorFactory $paginatorFactory,
Security $security
) {
$this->timelineBuilder = $timelineBuilder;
$this->paginatorFactory = $paginatorFactory;
$this->security = $security;
}
/**
* @Route("/{_locale}/center/timeline",
* name="chill_center_timeline",
* methods={"GET"}
* )
*/
public function centerAction(Request $request)
{
// collect reachable center for each group
$user = $this->security->getUser();
$centers = [];
foreach ($user->getGroupCenters() as $group) {
$centers[] = $group->getCenter();
}
if (0 === count($centers)) {
throw $this->createNotFoundException();
}
$nbItems = $this->timelineBuilder->countItems('center',
[ 'centers' => $centers ]
);
$paginator = $this->paginatorFactory->create($nbItems);
return $this->render('@ChillMain/Timeline/index.html.twig', array
(
'timeline' => $this->timelineBuilder->getTimelineHTML(
'center',
[ 'centers' => $centers ],
$paginator->getCurrentPage()->getFirstItemNumber(),
$paginator->getItemsPerPage()
),
'nb_items' => $nbItems,
'paginator' => $paginator
)
);
}
}

View File

@@ -0,0 +1,7 @@
<div class="timeline">
{% for result in results %}
<div class="timeline-item {% if loop.index0 is even %}even{% else %}odd{% endif %}">
{% include result.template with result.template_data %}
</div>
{% endfor %}
</div>

View File

@@ -1,7 +1,15 @@
<div class="timeline">
{% for result in results %}
<div class="timeline-item {% if loop.index0 is even %}even{% else %}odd{% endif %}">
{% include result.template with result.template_data %}
</div>
{% endfor %}
</div>
{% extends "@ChillMain/layout.html.twig" %}
{% block content %}
<div id="container content">
<div class="grid-8 centered">
<h1>{{ 'Global timeline'|trans }}</h1>
{{ timeline|raw }}
{% if nb_items > paginator.getItemsPerPage %}
{{ chill_pagination(paginator) }}
{% endif %}
</div>
</div>
{% endblock content %}

View File

@@ -23,6 +23,8 @@ use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\DBAL\Types\Type;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Doctrine\ORM\Query;
use Doctrine\ORM\NativeQuery;
/**
* Build timeline
@@ -78,14 +80,14 @@ class TimelineBuilder implements ContainerAwareInterface
*/
public function getTimelineHTML($context, array $args, $firstItem = 0, $number = 20)
{
$union = $this->buildUnionQuery($context, $args);
list($union, $parameters) = $this->buildUnionQuery($context, $args);
//add ORDER BY clause and LIMIT
$query = $union . sprintf(' ORDER BY date DESC LIMIT %d OFFSET %d',
$number, $firstItem);
// run query and handle results
$fetched = $this->runUnionQuery($query);
$fetched = $this->runUnionQuery($query, $parameters);
$entitiesByKey = $this->getEntities($fetched, $context);
return $this->render($fetched, $entitiesByKey, $context, $args);
@@ -100,16 +102,18 @@ class TimelineBuilder implements ContainerAwareInterface
*/
public function countItems($context, array $args)
{
$union = $this->buildUnionQuery($context, $args);
// embed the union query inside a count query
$count = sprintf('SELECT COUNT(sq.id) AS total FROM (%s) as sq', $union);
$rsm = (new ResultSetMapping())
->addScalarResult('total', 'total', Type::INTEGER);
list($select, $parameters) = $this->buildUnionQuery($context, $args);
// embed the union query inside a count query
$countQuery = sprintf('SELECT COUNT(sq.id) AS total FROM (%s) as sq', $select);
$nq = $this->em->createNativeQuery($countQuery, $rsm);
$nq->setParameters($parameters);
return $this->em->createNativeQuery($count, $rsm)
->getSingleScalarResult();
return $nq->getSingleScalarResult();
}
/**
@@ -154,40 +158,56 @@ class TimelineBuilder implements ContainerAwareInterface
*
* @uses self::buildSelectQuery to build individual SELECT queries
*
* @param string $context
* @param mixed $args
* @param int $page
* @param int $number
* @return string
* @throws \LogicException if no builder have been defined for this context
* @return array, where first element is the query, the second one an array with the parameters
*/
private function buildUnionQuery($context, array $args)
private function buildUnionQuery(string $context, array $args): array
{
//append SELECT queries with UNION keyword between them
$union = '';
$parameters = [];
foreach($this->getProvidersByContext($context) as $provider) {
$select = $this->buildSelectQuery($provider, $context, $args);
$append = ($union === '') ? $select : ' UNION '.$select;
$data = $provider->fetchQuery($context, $args);
list($select, $selectParameters) = $this->buildSelectQuery($data);
$append = empty($union) ? $select : ' UNION '.$select;
$union .= $append;
$parameters = array_merge($parameters, $selectParameters);
}
return $union;
return [$union, $parameters];
}
/**
* Hack to replace the arbitrary "AS" statement in DQL
* into proper SQL query
* TODO remove
private function replaceASInDQL(string $dql): string
{
$pattern = '/^(SELECT\s+[a-zA-Z0-9\_\.\']{1,}\s+)(AS [a-z0-9\_]{1,})(\s{0,},\s{0,}[a-zA-Z0-9\_\.\']{1,}\s+)(AS [a-z0-9\_]{1,})(\s{0,},\s{0,}[a-zA-Z0-9\_\.\']{1,}\s+)(AS [a-z0-9\_]{1,})(\s+FROM.*)/';
$replacements = '${1} AS id ${3} AS type ${5} AS date ${7}';
$s = \preg_replace($pattern, $replacements, $dql, 1);
if (NULL === $s) {
throw new \RuntimeException('Could not replace the "AS" statement produced by '.
'DQL with normal SQL AS: '.$dql);
}
return $s;
}
*/
/**
* return the SQL SELECT query as a string,
*
* @uses TimelineProfiderInterface::fetchQuery use the fetchQuery function
* @param \Chill\MainBundle\Timeline\TimelineProviderInterface $provider
* @param string $context
* @param mixed[] $args
* @return string
*/
private function buildSelectQuery(TimelineProviderInterface $provider, $context, array $args)
private function buildSelectQuery(array $data): array
{
$data = $provider->fetchQuery($context, $args);
return sprintf(
$parameters = [];
$sql = sprintf(
'SELECT %s AS id, '
. '%s AS "date", '
. "'%s' AS type "
@@ -197,16 +217,19 @@ class TimelineBuilder implements ContainerAwareInterface
$data['date'],
$data['type'],
$data['FROM'],
$data['WHERE']);
is_string($data['WHERE']) ? $data['WHERE'] : $data['WHERE'][0]
);
return [$sql, $data['WHERE'][1]];
}
/**
* run the UNION query and return result as an array
*
* @param string $query
* @return array
* @return array an array with the results
*/
private function runUnionQuery($query)
private function runUnionQuery(string $query, array $parameters): array
{
$resultSetMapping = (new ResultSetMapping())
->addScalarResult('id', 'id')
@@ -214,7 +237,8 @@ class TimelineBuilder implements ContainerAwareInterface
->addScalarResult('date', 'date');
return $this->em->createNativeQuery($query, $resultSetMapping)
->getArrayResult();
->setParameters($parameters)
->getArrayResult();
}
/**
@@ -274,7 +298,7 @@ class TimelineBuilder implements ContainerAwareInterface
}
return $this->container->get('templating')
->render('@ChillMain/Timeline/index.html.twig', array(
->render('@ChillMain/Timeline/chain_timelines.html.twig', array(
'results' => $timelineEntries
));

View File

@@ -1,3 +1,7 @@
chill_main_controllers:
resource: '../Controller/'
type: annotation
chill_main_admin_permissionsgroup:
resource: "@ChillMainBundle/config/routes/permissionsgroup.yaml"
prefix: "{_locale}/admin/permissionsgroup"

View File

@@ -4,4 +4,7 @@ services:
arguments:
- "@doctrine.orm.entity_manager"
calls:
- [ setContainer, ["@service_container"]]
- [ setContainer, ["@service_container"]]
# alias:
Chill\MainBundle\Timeline\TimelineBuilder: '@chill_main.timeline_builder'