AppExtension.php 15.8 KB
Newer Older
Julien Jorry committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
<?php

namespace App\Twig;

use App\Entity\AchatMonnaieAConfirmerAdherent;
use App\Entity\AchatMonnaieAConfirmerPrestataire;
use App\Entity\Adherent;
use App\Entity\Comptoir;
use App\Entity\Flux;
use App\Entity\GlobalParameter;
use App\Entity\Groupe;
use App\Entity\Groupeprestataire;
use App\Entity\News;
use App\Entity\Prestataire;
use App\Entity\Rubrique;
use App\Entity\Siege;
use App\Entity\User;
use App\Enum\CurrencyEnum;
use App\Flux\AccountableInterface;
use App\Utils\CotisationUtils;
use App\Utils\OperationUtils;
use Doctrine\ORM\EntityManagerInterface;
use FOS\UserBundle\Model\UserInterface;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\Security;
use Twig\Extension\AbstractExtension;
use Twig\TwigTest;

class AppExtension extends AbstractExtension
{
    public $em;
    public $security;
    public $container;
    public $paginator;
    public $session;
    public $operationUtils;
    public $cotisationUtils;

    public function __construct(ContainerInterface $container, Security $security, EntityManagerInterface $em, PaginatorInterface $paginator, SessionInterface $session, OperationUtils $operationUtils, CotisationUtils $cotisationUtils)
    {
        $this->em = $em;
        $this->security = $security;
        $this->container = $container;
        $this->paginator = $paginator;
        $this->session = $session;
        $this->operationUtils = $operationUtils;
        $this->cotisationUtils = $cotisationUtils;
    }

    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('getMLCPrestataire', [$this, 'getMLCPrestataire']),
            new \Twig_SimpleFunction('showModalGroupChoice', [$this, 'showModalGroupChoice']),
            new \Twig_SimpleFunction('getCurrentRole', [$this, 'getCurrentRole']),
            new \Twig_SimpleFunction('getCurrentComptoir', [$this, 'getCurrentComptoir']),
            new \Twig_SimpleFunction('getCurrentGroupe', [$this, 'getCurrentGroupe']),
            new \Twig_SimpleFunction('getCurrentPrestataire', [$this, 'getCurrentPrestataire']),
            new \Twig_SimpleFunction('isCotisationValid', [$this, 'isCotisationValid']),
63 64
            new \Twig_SimpleFunction('isCotisationValidForPresta', [$this, 'isCotisationValidForPresta']),
            new \Twig_SimpleFunction('isCotisationValidForAdherent', [$this, 'isCotisationValidForAdherent']),
Julien Jorry committed
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
            new \Twig_SimpleFunction('getSiege', [$this, 'getSiege']),
            new \Twig_SimpleFunction('isDevFixture', [$this, 'isDevFixture']),
            new \Twig_SimpleFunction('getLastNews', [$this, 'getLastNews']),
            new \Twig_SimpleFunction('getAllPrestataires', [$this, 'getAllPrestataires']),
            new \Twig_SimpleFunction('getAllGroupePrestataires', [$this, 'getAllGroupePrestataires']),
            new \Twig_SimpleFunction('getAllComptoirs', [$this, 'getAllComptoirs']),
            new \Twig_SimpleFunction('getAllRubriques', [$this, 'getAllRubriques']),
            new \Twig_SimpleFunction('getAllGroupes', [$this, 'getAllGroupes']),
            new \Twig_SimpleFunction('getAllFlux', [$this, 'getAllFlux']),
            new \Twig_SimpleFunction('isCurrentAccountable', [$this, 'isCurrentAccountable']),
            new \Twig_SimpleFunction('getDemandeAchatMonnaie', [$this, 'getDemandeAchatMonnaie']),
            new \Twig_SimpleFunction('hasDemandeAchatMonnaie', [$this, 'hasDemandeAchatMonnaie']),
            new \Twig_SimpleFunction('getLastOperations', [$this, 'getLastOperations']),
            new \Twig_SimpleFunction('mediaurl', [$this, 'mediaurl']),
            new \Twig_SimpleFunction('getWordpressApiKey', [$this, 'getWordpressApiKey']),
            new \Twig_SimpleFunction('getTotalMonnaieEmise', [$this, 'getTotalMonnaieEmise']),
            new \Twig_SimpleFunction('getStatsMonnaie', [$this, 'getStatsMonnaie']),
            new \Twig_SimpleFunction('getCurrencyName', [$this, 'getCurrencyName']),
            new \Twig_SimpleFunction('parameter', function ($name) {
                return $this->container->getParameter($name);
            }),
            new \Twig_SimpleFunction('isPayzenEnabled', [$this, 'isPayzenEnabled']),
        ];
    }

    public function getCurrencyName(string $currency): string
    {
        if (!in_array($currency, CurrencyEnum::getAvailableTypes())) {
            throw new \Exception('Opération impossible ! Type de currency  ' . $currency . ' inexistant !');
        }
        $symbol = $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::MLC_SYMBOL);
        switch ($currency) {
            case CurrencyEnum::CURRENCY_EMLC:
                return 'e' . $symbol;
            case CurrencyEnum::CURRENCY_MLC:
                return $symbol;
            case CurrencyEnum::CURRENCY_EURO:
                return '€';
            case CurrencyEnum::CURRENCY_MLC_NANTIE:
                return $symbol;
        }

        return '';
    }

    public function getMLCPrestataire(): ?Prestataire
    {
        try {
            $prestaMLC = $this->em->getRepository(Prestataire::class)->getPrestataireMLC();

            return $prestaMLC;
        } catch (\Exception $e) {
            return null;
        }

        return null;
    }

    public function isPayzenEnabled()
    {
        return 'true' === $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::USE_PAYZEN) ? true : false;
    }

    public function getFilters()
    {
        return [
            new \Twig_SimpleFilter('json_decode', [$this, 'jsonDecode']),
            new \Twig_SimpleFilter('safe_email', [$this, 'safeEmailFilter']),
        ];
    }

    public function jsonDecode($string)
    {
        return json_decode($string, true);
    }

    public function getWordpressApiKey()
    {
        $users = $this->em->getRepository(User::class)->findByRole('ROLE_API');
        if (count($users) <= 0) {
            // @TODO :erreur => crée un nouvel utilisateur API si non existant ?
            return '';
        }

        return $users[0]->getApiKey();
    }

    public function showModalGroupChoice()
    {
        if (null != $this->security->getUser()) {
            if (count($this->security->getUser()->getPossiblegroups()) > 1 && 0 == count($this->security->getUser()->getGroups())) {
                return true;
            }
        }

        return false;
    }

    public function getCurrentRole()
    {
        $return = $this->security->getUser()->getGroups()[0]->getName();
        $user = $this->security->getUser();
        if (null != $this->session->get('_prestagere') && $user->isGranted('ROLE_PRESTATAIRE')) {
            $presta = $this->session->get('_prestagere');
169
            $presta = $this->em->getRepository(Prestataire::class)->findOneById($presta->getId());
Julien Jorry committed
170 171 172 173 174
            $return .= '<br/>' . $presta->__toString();
        } elseif (null != $user->getAdherent() && $user->isGranted('ROLE_ADHERENT')) {
            $return .= '<br/>' . $user->getAdherent()->__toString();
        } elseif (null != $this->session->get('_comptoirgere') && $user->isGranted('ROLE_COMPTOIR')) {
            $comptoir = $this->session->get('_comptoirgere');
175
            $comptoir = $this->em->getRepository(Comptoir::class)->findOneById($comptoir->getId());
Julien Jorry committed
176 177 178
            $return .= '<br/>' . $comptoir->__toString();
        } elseif (null != $this->session->get('_groupegere') && $user->isGranted('ROLE_GESTION_GROUPE')) {
            $groupe = $this->session->get('_groupegere');
179
            $groupe = $this->em->getRepository(Groupe::class)->findOneById($groupe->getId());
Julien Jorry committed
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
            $return .= '<br/>' . $groupe->__toString();
        }

        return $return;
    }

    public function getCurrentComptoir()
    {
        if (!$this->session->has('_comptoirgere')) {
            return null;
        }

        return $this->em->getRepository(Comptoir::class)->findOneById($this->session->get('_comptoirgere')->getId());
    }

    public function getCurrentGroupe()
    {
        if (!$this->session->has('_groupegere')) {
            return null;
        }

        return $this->em->getRepository(Groupe::class)->findOneById($this->session->get('_groupegere')->getId());
    }

    public function getCurrentPrestataire()
    {
        if (!$this->session->has('_prestagere')) {
            return null;
        }

        return $this->em->getRepository(Prestataire::class)->findOneById($this->session->get('_prestagere')->getId());
    }

213
    /**
214 215 216 217 218
     * isCotisationValid.
     *
     * @param UserInterface|null $user
     *
     * @return bool|date
219 220
     */
    public function isCotisationValid(?UserInterface $user = null)
Julien Jorry committed
221 222 223 224
    {
        return $this->cotisationUtils->isCotisationValid($user);
    }

225
    /**
226 227 228 229 230
     * [isCotisationValidForPresta.
     *
     * @param Prestataire|null $presta
     *
     * @return bool|date
231 232
     */
    public function isCotisationValidForPresta(?Prestataire $presta = null)
233 234 235 236
    {
        return $this->cotisationUtils->isCotisationValidForPresta($presta);
    }

237
    /**
238 239 240 241 242
     * [isCotisationValidForAdherent.
     *
     * @param Adherent|null $adherent
     *
     * @return bool|date
243 244
     */
    public function isCotisationValidForAdherent(?Adherent $adherent = null)
245 246 247 248
    {
        return $this->cotisationUtils->isCotisationValidForAdherent($adherent);
    }

Julien Jorry committed
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    public function isDevFixture(?string $username = null)
    {
        if (null == $username) {
            $user = $this->em->getRepository(User::class)->findBy(['username' => ['user_redacteur', 'user_tresorier', 'user_prestataire', 'user_contact']]);

            return 4 === count($user);
        }

        return null != $this->em->getRepository(User::class)->findOneByUsername($username);
    }

    public function getSiege()
    {
        return $this->em->getRepository(Siege::class)->getTheOne();
    }

    public function getLastNews($limit = 5)
    {
267
        return $this->em->getRepository(News::class)->findLatest($limit)->getResult();
Julien Jorry committed
268 269
    }

270
    public function getAllPrestataires($orderBy = 'raison', $direction = 'ASC', $limit = null)
Julien Jorry committed
271
    {
272
        return $this->em->getRepository(Prestataire::class)->findDefault('all', $orderBy, $direction, $limit);
Julien Jorry committed
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
    }

    public function getAllGroupePrestataires($type = '')
    {
        if (!empty($type)) {
            return $this->em->getRepository(Groupeprestataire::class)->findBy(['type' => $type, 'enabled' => true]);
        }

        return $this->em->getRepository(Groupeprestataire::class)->findBy(['enabled' => true]);
    }

    public function getAllComptoirs()
    {
        return $this->em->getRepository(Comptoir::class)->findBy(['enabled' => true], ['name' => 'ASC']);
    }

    public function getAllRubriques()
    {
        return $this->em->getRepository(Rubrique::class)->findBy(['enabled' => true], ['name' => 'ASC']);
    }

    public function isCurrentAccountable(User $user, AccountableInterface $object)
    {
        $obj = $this->operationUtils->getCurrentAccountable($user);
        if ($obj->getId() == $object->getId() && get_class($obj) == get_class($object)) {
            return true;
        }

        return false;
    }

    public function getDemandeAchatMonnaie($reconverti = true)
    {
        $obj = $this->operationUtils->getCurrentAccountable($this->security->getUser());
        if ($obj instanceof Prestataire) {
            $q = $this->em->getRepository(AchatMonnaieAConfirmerPrestataire::class)->findBy(['destinataire' => $obj, 'reconverti' => $reconverti], ['createdAt' => 'DESC']);
        } elseif ($obj instanceof Adherent) {
            $q = $this->em->getRepository(AchatMonnaieAConfirmerAdherent::class)->findBy(['destinataire' => $obj, 'reconverti' => $reconverti], ['createdAt' => 'DESC']);
        }

        return $q;
    }

    public function hasDemandeAchatMonnaie($reconverti = true): bool
    {
        $q = $this->getDemandeAchatMonnaie($reconverti);

        return null != $q && count($q) > 0;
    }

    public function getTotalMonnaieEmise(): float
    {
        $return = $this->em->getRepository(Flux::class)->getTotalVenteAchat();
        if (null == $return) {
            return 0;
        }

        return $return;
    }

    public function getStatsMonnaie(string $currency = CurrencyEnum::CURRENCY_EMLC): float
    {
        $siege = $this->em->getRepository(Siege::class)->getTheOne();

        if (!empty($currency)) {
            if (!in_array($currency, [CurrencyEnum::CURRENCY_EMLC, CurrencyEnum::CURRENCY_MLC_NANTIE])) {
                return (float) 0;
            }

            return $siege->getAccountWithCurrency($currency)->getBalance();
        }

        return $siege->getEmlcAccount()->getBalance();
    }

    public function getLastOperations(Request $request, User $user, string $currency = null, int $limit = 10)
    {
        $query = $this->operationUtils->getUserOperationsByCurrency($request, $currency);

        return $query->getResult();
        if (null != $query) {
            $pagination = $this->paginator->paginate(
                $query, /* query NOT result */
                $request->query->getInt('page', 1)/*page number*/ ,
                $limit/*limit per page*/
            );

            return $pagination;
        }

        return null;
    }

    public function getAllFlux(User $user, Request $request, $parenttype = null)
    {
        $query = null;
        if (null != $this->session->get('_prestagere')) {
            if ($this->security->isGranted('ROLE_PRESTATAIRE')) {
                $query = $this->em->getRepository(Flux::class)->getQueryByPrestataire($this->session->get('_prestagere'), $parenttype);
            } elseif ($this->security->isGranted('ROLE_CAISSIER')) {
                $query = $this->em->getRepository(Flux::class)->getQueryByCaissier($this->session->get('_prestagere'));
            }
        } elseif (null != $user->getAdherent()) {
            $query = $this->em->getRepository(Flux::class)->getQueryByAdherent($user->getAdherent(), $parenttype);
        } elseif (null != $this->session->get('_comptoirgere')) {
            $query = $this->em->getRepository(Flux::class)->getQueryByComptoir($this->session->get('_comptoirgere'));
        } elseif (null != $this->session->get('_groupegere')) {
            $query = $this->em->getRepository(Flux::class)->getQueryByGroupe($this->session->get('_groupegere'));
        }
        if (null != $query) {
            $pagination = $this->paginator->paginate(
                $query, /* query NOT result */
                $request->query->getInt('page', 1)/*page number*/ ,
                10/*limit per page*/
            );

            return $pagination;
        }

        return null;
    }

    public function getAllGroupes()
    {
        return $this->em->getRepository(Groupe::class)->findBy(['enabled' => true], ['name' => 'ASC']);
    }

    public function mediaurl($media, $format)
    {
        $provider = $this->container->get($media->getProviderName());

        return $provider->generatePublicUrl($media, $format);
    }

    public function getTests(): array
    {
        return [
            new TwigTest('instanceof', [$this, 'instanceof']),
        ];
    }

    public function instanceof($var, $instance)
    {
        $reflexionClass = new \ReflectionClass($instance);

        return $reflexionClass->isInstance($var);
    }

    /**
     * Protects email address.
     * (inspired by : https://github.com/getgrav/grav/blob/develop/system/src/Grav/Common/Twig/TwigExtension.php ).
     *
     * @param string $str
     *
     * @return string
     */
    public function safeEmailFilter($str)
    {
        $email = '';
        for ($i = 0, $len = strlen($str); $i < $len; ++$i) {
            $j = mt_rand(0, 1);
            if (0 === $j) {
                $email .= '&#' . ord($str[$i]) . ';';
            } elseif (1 === $j) {
                $email .= $str[$i];
            }
        }

        return str_replace('@', '&#64;', $email);
    }
}