<?php
namespace App\Twig;
use App\Application\Sonata\MediaBundle\Entity\Media;
use App\Entity\Boutique\Panier;
use App\Entity\Boutique\Produit;
use App\Entity\Boutique\ProduitDeclinaison;
use App\Entity\Boutique\ProduitReducCe;
use App\Entity\Boutique\Promotion;
use App\Manager\Boutique\ProduitManager;
use App\Manager\Boutique\ProduitStockBalanceManager;
use App\Manager\Categorie\CategorieManager;
use App\Utils\Toolbox;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Intl\Intl;
use App\Entity\Contenu\Page;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Liip\ImagineBundle\Service\FilterService;
use Sonata\MediaBundle\Model\MediaInterface;
use Sonata\MediaBundle\Provider\ImageProvider;
class AppRuntime
{
private $provider;
private $filterService;
private $router;
private $requestStack;
private $categorieManager;
private $locales;
private $defaultLocale;
private $kernel;
/**
* @var ProduitManager
*/
private $produitManager;
/**
* @var ProduitStockBalanceManager
*/
private $produitStockBalanceManager;
/**
* @var EntityManagerInterface
*/
private $entityManager;
public function __construct(
ImageProvider $provider,
FilterService $filterService,
UrlGeneratorInterface $router,
RequestStack $requestStack,
CategorieManager $categorieManager,
ProduitManager $produitManager,
string $locales,
string $defaultLocale,
EntityManagerInterface $entityManager,
KernelInterface $kernel,
ProduitStockBalanceManager $produitStockBalanceManager
)
{
$this->provider = $provider;
$this->filterService = $filterService;
$this->router = $router;
$this->requestStack = $requestStack;
$this->categorieManager = $categorieManager;
$this->locales = $locales;
$this->defaultLocale = $defaultLocale;
$this->kernel = $kernel;
$this->produitManager = $produitManager;
$this->produitStockBalanceManager = $produitStockBalanceManager;
$this->entityManager = $entityManager;
}
public function ireplace(string $subject, array $replacement = []): ?string
{
return str_ireplace(array_keys($replacement), array_values($replacement), $subject);
}
public function fileExists(string $file)
{
if (false === preg_match('#^\/#', $file)) {
$file = '/'.$file;
}
if (false === preg_match('#^\.#', $file)) {
$file = '.'.$file;
}
return file_exists($this->kernel->getProjectDir().$file);
}
public function pregReplace(string $pattern, string $replacement, string $subject): ?string
{
return preg_replace($pattern, $replacement, $subject);
}
public function stringToUrl(string $string, string $separator = '-', bool $isImage = false): ?string
{
return Toolbox::stringToUrl($string, $separator, $isImage);
}
public function sonataMedia(?MediaInterface $media, ?string $filter = null, array $data = []): string
{
if (count($data)) {
$media = new Media();
foreach ($data as $key => $val) {
$method = 'set'.ucfirst($key);
if (method_exists($media, $method)) {
$media->$method($val);
}
}
}
if (is_null($filter)) {
$path = $this->provider->generatePublicUrl($media, 'reference');
} else {
$path = '/media/'.$this->provider->generatePath($media).'/'.$media->getProviderReference();
try {
$path = $this->filterService->getUrlOfFilteredImage($path, $filter);
} catch (\Exception $e) {
}
}
return $path;
}
public function getLocales(?string $locale = null, $excludeSpecifiedLocale = false): array
{
$localeCodes = explode('|', $this->locales);
$locales = [];
foreach ($localeCodes as $localeCode) {
$locales[$localeCode] = ['code' => $localeCode, 'name' => Intl::getLocaleBundle()->getLocaleName($localeCode, $localeCode)];
}
if (!is_null($locale) && isset($locales[$locale]) && true === $excludeSpecifiedLocale) {
unset($locales[$locale]);
}
if (!is_null($locale) && isset($locales[$locale]) && false === $excludeSpecifiedLocale) {
return $locales[$locale];
}
return $locales;
}
public function generateUrl($object): string
{
if ($object instanceof Page) {
try {
$parameters = $this->router->match('/'.$object->getSlug());
if (isset($parameters['_route'])) {
return $this->router->generate($parameters['_route']);
}
}
catch (ResourceNotFoundException $e) {
return $this->router->generate('page.detail', [
'slug' => $object->getSlug()
]);
}
}
return '';
}
public function prettify(?string $string = null): ?string
{
$pattern = '/\*(.*?)\*/';
$replacement = '<span>$1</span>';
return preg_replace($pattern, $replacement, $string);
}
public function wysiswygFormatter(?string $string = null): ?string
{
if (is_null($string)) {
$string = '';
}
// Tableaux
$string = str_replace('<table', '<div class="table-responsive"><table class="table table-hover"', $string);
$string = str_replace('</table>', '</table></div>', $string);
$string = preg_replace('/(<[^>]+) cellspacing=".*?"/i', '$1', $string);
$string = preg_replace('/(<[^>]+) cellpadding=".*?"/i', '$1', $string);
$string = preg_replace('/(<[^>]+) border=".*?"/i', '$1', $string);
// Images
$string = str_replace('<img', '<img class="img-wysiwyg"', $string);
// $string = preg_replace('/(<[^>]+) style=".*?"/i', '$1', $string);
// Liens
$string = str_replace('.pdf"', '.pdf" class="link-pdf"', $string);
// Nettoyage styles word
$string = preg_replace('/(<[^>]+) color=".*?"/i', '$1', $string);
$string = preg_replace('/(<[^>]+) size=".*?"/i', '$1', $string);
$string = preg_replace('/(<[^>]+) face=".*?"/i', '$1', $string);
$string = preg_replace('/(<[^>]+) width=".*?"/i', '$1', $string);
$string = preg_replace('/(<[^>]+) bgcolor=".*?"/i', '$1', $string);
$string = preg_replace('/(<[^>]+) cellspacing=".*?"/i', '$1', $string);
$string = preg_replace('/(<[^>]+) cellpadding=".*?"/i', '$1', $string);
$string = preg_replace('/(<[^>]+) border=".*?"/i', '$1', $string);
return $string;
}
public function localeName($locale){
return Intl::getLocaleBundle()->getLocaleName($locale);
}
public function getCategorieChemin($categorie): string
{
$className = (new \ReflectionClass($categorie))->getShortName();
$requestStack = $this->requestStack->getCurrentRequest();
$arborescence = array_reverse($this->categorieManager->getRecursiveCategorieParent($categorie));
$categories = [];
foreach ($arborescence as $categorie) {
$url = $this->router->generate('admin_app_boutique_'.strtolower($className).'_edit', array_merge(['id' => $categorie->getId()], $requestStack->query->all()));
$categories[] = '<a href="'.$url.'" class="sonata-link-identifier">'.$categorie->getIntitule().'</a>';
}
if (count($categories)) {
return implode(' <span>></span> ', $categories);
}
return '';
}
public function getCategorieIcone($categorie): string
{
$icone = $this->categorieManager->getCategorieIcone($categorie);
return $icone;
}
public function getCategorieRootIntitule($categorie)
{
$arborescence = $this->categorieManager->getRecursiveCategorieParent($categorie);
if (isset($arborescence[0])) {
return $arborescence[0]->getIntitule();
}
return null;
}
public function getMontantPromotionUtilisePanier(Panier $panier, Promotion $promotion): string
{
$montant = 0;
foreach ($panier->getLignes() as $ligne) {
if ($ligne->getPromotion() == $promotion) {
$entite = $ligne->getProduit();
if (!is_null($ligne->getProduitDeclinaison())) {
$entite = $ligne->getProduitDeclinaison();
}
list($prixVenteTtcAvecRemise, $appliquerPromotion) = $this->produitManager->getPrixVenteTtcAvecRemise($entite, $promotion, true);
$montantLigne = (($ligne->getMontantTtc() - $prixVenteTtcAvecRemise) * $ligne->getQuantite());
if (!is_null($ligne->getRemiseMontantMax()) && $montantLigne > $ligne->getRemiseMontantMax()) {
$montantLigne = $ligne->getRemiseMontantMax();
}
$montant += $montantLigne;
}
}
if (!is_null($promotion->getPlafondPeriode()) && $montant > $promotion->getPlafondPeriode()) {
$montant = $promotion->getPlafondPeriode();
}
return $montant;
}
public function getMontantPromotionUtiliseApresPanier(Panier $panier, Promotion $promotion): ?string
{
// Si pas de plafond configuré on affiche pas le montant restant
if (is_null($promotion->getPlafondPeriode()) && is_null($promotion->getRemisePlafond())) {
return null;
}
list($nombreUtilisationCommande, $montantUtilisationCommande) = $this->produitManager->getUtilisateurHistoriquePromotionCommande($promotion);
$montant = $montantUtilisationCommande;
$montant += $this->getMontantPromotionUtilisePanier($panier, $promotion);
if (!is_null($promotion->getPlafondPeriode()) && $montant > $promotion->getPlafondPeriode()) {
$montant = $promotion->getPlafondPeriode();
}
$montantRestant = $promotion->getPlafondPeriode() - $montant;
if (!is_null($promotion->getRemisePlafond())) {
$montantRestant = $promotion->getRemisePlafond() + $montantRestant;
}
if ($montantRestant > 0) {
return $montantRestant;
}
return 0;
}
public function produitDefaultImage($produit = null, $taille = '800_533_thumbnail')
{
$catalogueId = null;
if (is_object($produit) && !is_null($produit->getProduitReducCe())) {
$catalogueId = $produit->getProduitReducCe()->getCataloguesId();
}
if (is_array($produit) && isset($produit['produitReducCe'])) {
$catalogueId = $produit['produitReducCe']['cataloguesId'];
}
$miniature = 'build/img/ticket-spectacle_'.$taille.'.jpg';
if (getenv('APP_SITE_SLUG') == 'horizonce' && $catalogueId == ProduitReducCe::CATALOGUE_REDUCTICKET) {
$miniature = 'build/img/ticket-concert_'.$taille.'.jpg';
}
return $miniature;
}
public function xmlEscape($string)
{
return str_replace(array('&', '<', '>', '\'', '"'), array('&', '<', '>', ''', '"'), $string);
}
public function unescape($string)
{
return html_entity_decode($string, ENT_QUOTES, 'UTF-8');
}
/**
* @param Produit|null $produit
* @param ProduitDeclinaison|null $produitDeclinaison
*
* @return int
*/
public function getStock(?Produit $produit = null, ?ProduitDeclinaison $produitDeclinaison = null): int
{
return $this->produitStockBalanceManager->getStock($produit, $produitDeclinaison);
}
/**
* @param Produit $produit
*
* @return int
*/
public function getStockTotalProduitDeclinaisons(Produit $produit): int
{
$stock = 0;
foreach ($produit->getProduitDeclinaisonsVisibles() as $produitDeclinaison) {
$stock += $this->produitStockBalanceManager->getStock(null, $produitDeclinaison);
}
return $stock;
}
/**
* @param int $id
* @param mixed $class
* @param string $field
*
* @return string
*/
public function getObjectStringFromId(int $id, $class, string $field): string
{
$object = $this->entityManager->getRepository($class)->find($id);
$getter = 'get'.ucfirst($field);
return trim($object->$getter());
}
}