<?php
namespace App\Controller\API;
use App\Entity\Attachment;
use App\Entity\Collection;
use App\Entity\Color;
use App\Entity\Country;
use App\Entity\KindProject;
use App\Entity\Newsletter;
use App\Entity\Product;
use App\Entity\Project;
use App\Entity\Section;
use App\Entity\Shape;
use App\Entity\User;
use App\Service\DocumentFileUploader;
use App\Service\FilePathAndUrlService;
use App\Service\LocaleService;
use App\Service\SearchService;
use App\Traits\AttachmentUrls;
use MailchimpTransactional\ApiClient;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Intl\Countries;
use Symfony\Component\Intl\Languages;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Constraints\Json;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\Validator\Constraints\Email as ConstraintEmail;
class ApiController extends AbstractController
{
use AttachmentUrls;
private $translator;
private $localeService;
private $filePathAndUrlService;
protected $documentFileUploader;
private $translatorService;
public function __construct(TranslatorInterface $translator, LocaleService $localeService, $translatorService,
FilePathAndUrlService $filePathAndUrlService, DocumentFileUploader $documentFileUploader)
{
$this->translator = $translator;
$this->localeService = $localeService;
$this->filePathAndUrlService = $filePathAndUrlService;
$this->documentFileUploader = $documentFileUploader;
$this->translatorService = $translatorService;
}
/**
* @Route("/translations/{locale}", name="translations", methods={"GET"})
*/
public function getAllTranslations($locale, $noJSON = false) {
$this->translatorService->setLocale($locale);
$translations = $this->translatorService->getCatalogue()->all('messages');
if ($noJSON)
return $translations;
return new JsonResponse(['translations' => $translations]);
}
/**
* @Route("/urls/language/{locale}", name="route_links", methods={"GET"})
*/
public function getAllRouteLink($locale) {
return new JsonResponse([
'routes' => [
'home' => $this->generateUrl('pages_home_index', ['_locale' => $locale]),
'projects' => $this->generateUrl('pages_projects_overview', ['_locale' => $locale]),
'projectsFilterByProduct' => $this->generateUrl('pages_projects_filter_by_products', ['_locale' => $locale, 'productSlug' => 'productSlug']),
'projectsFilterByCountry' => $this->generateUrl('pages_projects_filter_by_countries', ['_locale' => $locale, 'alpha2' => 'alpha2']),
'projectsFilterByKindProject' => $this->generateUrl('pages_projects_filter_by_kind_project', ['_locale' => $locale, 'kindProjectSlug' => 'kindProjectSlug']),
'products' => $this->generateUrl('pages_products_overview', ['_locale' => $locale]),
'productsFilterByColor' => $this->generateUrl('pages_products_filter_by_colors', ['_locale' => $locale, 'colorSlug' => 'colorSlug']),
'productsFilterByShape' => $this->generateUrl('pages_products_filter_by_shapes', ['_locale' => $locale, 'shapeSlug' => 'shapeSlug']),
'productsFilterByProduct' => $this->generateUrl('pages_products_filter_by_products', ['_locale' => $locale, 'productSlug' => 'productSlug']),
'productsFilterByCollection' => $this->generateUrl('pages_products_filter_by_collection', ['_locale' => $locale, 'collectionSlug' => 'collectionSlug']),
'collections' => $this->generateUrl('pages_collections_overview', ['_locale' => $locale]),
'3DSimulation' => $this->generateUrl('pages_3d_simulation_index', ['_locale' => $locale]),
'samples' => $this->generateUrl('pages_sample_index', ['_locale' => $locale]),
'contact' => 'https://carpet-tiles.jp/ja/pages/contact',
]
]);
}
/**
* @Route("/technical-details/product/{name}/language/{locale}", name="technical_details", methods={"GET"})
*/
public function getTechnicalDetails($name, $locale, Request $request) {
$product = $this->getDoctrine()->getRepository(Product::class)->findOneBy(['name' => $name]);
$request->setLocale($locale);
if (! $product) {
return new JsonResponse([
'error' => 'no product find with name : ' . $name
]);
}
$collection = $product->getCollection();
$format = $collection->getTile() ? $this->translator->trans('Available all',[],null, $locale) : $this->translator->trans('Available roll',[],null, $locale);
$array = [
$collection->ismonolithic() ? $this->translator->trans('Monolithic',[],null,$locale) : null,
$collection->isBrick() ? $this->translator->trans('Brick',[],null, $locale) : null,
$collection->isAshlar()? $this->translator->trans('Ashlar',[],null, $locale) : null];
$installation = '';
foreach ($array as $item) {
if ($item)
$installation = $item .', ';
}
if (strlen($installation) > 2)
$installation = substr($installation,0, -2);
return new JsonResponse([
'technical-details-translation' => $this->translator->trans('Technical details',[],null, $locale),
'technical-details' => [
'format-translation' => $this->translator->trans('Format',[],null, $locale),
'format' => $format,
'installation-translation' => $this->translator->trans('Installation',[],null, $locale),
'installation' => $installation,
'composition-translation' => $this->translator->trans('Composition',[],null, $locale),
'composition' => $this->translator->trans('Composition description',[],null, $locale),
'warranty-translation' => $this->translator->trans('Warranty',[],null, $locale),
'warranty' => $this->translator->trans('Warranty 10 years',[],null, $locale),
'total-thickness-translation' => $this->translator->trans('Total thickness',[],null, $locale),
'total-thickness' => $this->translator->trans('Total thickness description',[],null, $locale),
'total-weight-translation' => $this->translator->trans('Total weight',[],null, $locale),
'total-weight' => $this->translator->trans('Total weight description',[],null, $locale),
'tile-size-translation' => $this->translator->trans('Tile size',[],null, $locale),
'tile-size' => $this->translator->trans('Tile size description',[],null, $locale),
'level-of-use-translation' => $this->translator->trans('Level of use',[],null, $locale),
'level-of-use' => $this->translator->trans('Level of use description',[],null, $locale),
'reaction-to-fire-translation' => $this->translator->trans('Reaction to fire',[],null, $locale),
'reaction-to-fire' => $this->translator->trans('Reaction to fire description',[],null, $locale),
'impact-sound-reduction-translation' => $this->translator->trans('Impact sound reduction',[],null, $locale),
'impact-sound-reduction' => $this->translator->trans('Impact sound reduction description',[],null, $locale),
],
]);
}
/**
* @Route("/currentLanguage", name="get_currentLocale", methods={"GET"})
*/
public function getCurrentLocale(Request $request, SessionInterface $sessiont, $noJSON = false) {
$session = $request->getSession();
$session->start();
$sessiont->start();
if ($noJSON)
return $request->getLocale();
return new JsonResponse(['currentLocale' => $request->getLocale()]);
}
/**
* @Route("/languages", name="get_locales", methods={"GET"})
*/
public function getAllLocales($noJSON = false)
{
if ($noJSON)
return $this->localeService->getLocales();
return new JsonResponse(['currentLocale' => $this->localeService->getLocales()]);
}
/**
* @Route("/products/genericPDFs", name="get_generic_pdfs", methods={"GET","POST"})
*/
public function getGenericPDFs(Request $request, $noJSON = false) {
$productsId = json_decode($request->getContent())->products;
$products = [];
if (is_array($productsId)) {
foreach ($productsId as $productId) {
$products[] = $this->getDoctrine()->getRepository(Product::class)->find($productId);
}
if ($noJSON)
return $this->documentFileUploader->getGenericPDF($products, $request);
return $this->sendResponse(['documents' => $this->documentFileUploader->getGenericPDF($products, $request)]);
}
return new JsonResponse([
'error' => 'wrong data format pass to the API.'
]);
}
/**
* @Route("/{locale}/countries", methods={"GET"})
*/
public function getCountries(Request $request, $locale, $noJSON = false) {
$countries = Countries::getNames($locale);
$result = [];
$i = 0;
foreach ($countries as $key => $country) {
$result[$i]['name'] = $country;
$result[$i]['id'] = $i;
$result[$i]['alpha2'] = $key;
$i++;
}
if ($noJSON)
return $result;
return $this->sendResponse(['countries' => $result]);
}
/**
* @Route("/{locale}/2tec2Countries", name="get_all_countries", methods={"GET"})
*/
public function getAllCountries($locale, $noJSON = false) {
$activeCountries = $this->getDoctrine()->getRepository(Country::class)->findCountryWithProjects();
$countries = Countries::getNames($locale);
$result = [];
//dd([$activeCountries, $countries]);
foreach ($countries as $alphaTwo => $country) {
foreach ($activeCountries as $activeCountry) {
if ($alphaTwo === $activeCountry->getAlpha2()) {
$activeCountry->setName($country);
$result[] = $activeCountry;
}
}
}
if ($noJSON)
return $result;
return $this->sendResponse(['countries' => $result]);
}
/**
* @Route("/{locale}/colors", name="get_all_colors", methods={"GET"})
*/
public function getAllColors($locale, $noJSON = false) {
$colors = $this->localeService->getAllEntitiesTranslated(Color::class, $locale);
if ($noJSON)
return $colors;
return $this->sendResponse(['colors' => $colors]);
}
/**
* @Route("/{locale}/shapes", name="get_all_shapes", methods={"GET"})
*/
public function getAllShapes($locale, $noJSON = false) {
$shapes = $this->localeService->getAllEntitiesTranslated(Shape::class, $locale);
if ($noJSON)
return $shapes;
return $this->sendResponse(['shapes' => $shapes]);
}
/**
* @Route("/{locale}/projects/filter/country/{alpha2}", methods={"GET"})
*/
public function getProjectsFilterByCountry($locale, $alpha2, $noJSON = false) {
$country = $this->getDoctrine()->getRepository(Country::class)->findOneBy(['alpha2' => strtoupper($alpha2)]);
$projects = [];
foreach ($this->getDoctrine()->getRepository(Project::class)->findBy(['country' => $country->getId()]) as $project) {
if ($project->getActif())
$projects[] = $project;
}
usort($projects, function($a, $b) {
return $a->getCreatedAt() < $b->getCreatedAt();
});
$this->setAttachmentUrls($projects, $this->filePathAndUrlService);
$this->localeService->setEntitiesTranslated($projects, $locale);
if ($noJSON)
return $projects;
return $this->sendResponse(['projects' => $projects]);
}
/**
* @Route("/{locale}/projects/filter/product/{productSlug}", methods={"GET"})
*/
public function getProjectsFilterByProduct($locale, $productSlug, $noJSON = false) {
$projects = [];
$allProjects = $this->localeService->getAllEntitiesTranslated(Project::class, $locale);
$currentProduct = $this->getDoctrine()->getRepository(Product::class)->projectsFilterByProduct($productSlug);
foreach ($allProjects as $project){
foreach ($project->getProducts() as $product) {
if ($product->getId() === $currentProduct->getId() && $project->getActif()) {
$projects[] = $project;
}
}
}
usort($projects, function($a, $b) {
return $a->getCreatedAt() < $b->getCreatedAt();
});
$this->setAttachmentUrls($projects, $this->filePathAndUrlService);
if ($noJSON)
return $projects;
return $this->sendResponse(['projects' => $projects]);
}
/**
* @Route("/{locale}/projects/filter/kindProject/{kindProjectSlug}", methods={"GET"})
*/
public function getProjectsFilterByKindProjects($locale, $kindProjectSlug, $noJSON = false) {
$projects = array();
$currentKind = null;
$allProjects = $this->localeService->getAllEntitiesTranslated(Project::class, $locale);
foreach ($this->getAllKindProjects($locale, true) as $kind) {
if ($kind->getSlug() === $kindProjectSlug)
$currentKind = $kind;
}
foreach ($allProjects as $project) {
if ($currentKind !== null && $project->getKindProject()->getId() === $currentKind->getId() && $project->getActif()) {
$projects[] = $project;
}
}
usort($projects, function($a, $b) {
return $a->getCreatedAt() < $b->getCreatedAt();
});
$this->setAttachmentUrls($projects, $this->filePathAndUrlService);
if ($noJSON)
return $projects;
return $this->sendResponse(['projects' => $projects]);
}
/**
* @Route("/{locale}/projects", name="get_all_projects", methods={"GET"})
*/
public function getAllProjects($locale, $noJSON = false) {
$projects = [];
foreach ($this->localeService->getAllEntitiesTranslated(Project::class, $locale) as $project) {
if ($project->getActif())
$projects[] = $project;
}
usort($projects, function($a, $b) {
return $a->getCreatedAt() < $b->getCreatedAt();
});
$this->setAttachmentUrls($projects, $this->filePathAndUrlService);
if ($noJSON)
return $projects;
return $this->sendResponse(['projects' => $projects]);
}
/**
* @Route("/{locale}/products/filter/shapes/{shapeSlug}", methods={"GET"})
*/
public function getProductsFilterByShape($locale, $shapeSlug, $noJSON = false)
{
$products = [];
$allProducts = $this->localeService->getAllEntitiesTranslated(Product::class, $locale);
if ($shapeSlug !== 'rolls') {
$collections = $this->getDoctrine()->getRepository(Collection::class)->findBy(['tile' => 1]);
} else {
$collections = $this->getDoctrine()->getRepository(Collection::class)->findAll();
}
foreach ($allProducts as $product) {
foreach ($collections as $collection) {
if ($collection === $product->getCollection() && $product->getActif() && $product->getCollection()->getActif()) {
$products[] = $product;
}
}
}
$this->setAttachmentUrls($products, $this->filePathAndUrlService);
if ($noJSON)
return $products;
return $this->sendResponse(['products' => $products]);
}
/**
* @Route("/{locale}/products/filter/collection/{collectionSlug}", methods={"GET"})
*/
public function getProductsFilterByCollection($locale, $collectionSlug, $noJSON = false) {
$products = [];
$allProducts = $this->localeService->getAllEntitiesTranslated(Product::class, $locale);
$currentCollection = $this->getDoctrine()->getRepository(Collection::class)->findOneBy(['slug' => $collectionSlug]);
foreach ($allProducts as $product) {
if ($currentCollection->getId() === $product->getCollection()->getId() && $product->getActif() && $product->getCollection()->getActif()) {
$products[] = $product;
}
}
$this->setAttachmentUrls($products, $this->filePathAndUrlService);
if ($noJSON)
return $products;
return $this->sendResponse(['products' => $products]);
}
/**
* @Route("/{locale}/products/filter/color/{colorSlug}", methods={"GET"})
*/
public function getProductsFilterByColor($locale, $colorSlug, $noJSON = false) {
$products = [];
$currentColor = null;
$allProducts = $this->localeService->getAllEntitiesTranslated(Product::class, $locale);
$colors = $this->getAllColors($locale, true);
foreach ($colors as $color) {
if ($color->getSlug() === $colorSlug)
$currentColor = $color;
}
foreach ($allProducts as $product) {
foreach ($product->getColors() as $color) {
if ($currentColor !== null && $currentColor->getId() === $color->getId() && $product->getActif() && $product->getCollection()->getActif()) {
$products[] = $product;
}
}
}
$this->setAttachmentUrls($products, $this->filePathAndUrlService);
if ($noJSON)
return $products;
return $this->sendResponse(['products' => $products]);
}
/**
* @Route("/{locale}/products/filter/product/{productSlug}", methods={"GET"})
*/
public function getProductsFilterByproduct($locale, $productSlug, $noJSON = false) {
$product = $this->getDoctrine()->getRepository(Product::class)->findOneBy(['slug' => $productSlug]);
$product = $this->localeService->getEntityTranslated(Product::class, $product->getId(), $locale);
$products[] = $product;
$this->setAttachmentUrls($products, $this->filePathAndUrlService);
if ($noJSON)
return $products;
return $this->sendResponse(['products' => $products]);
}
/**
* @Route("/{locale}/products/orderBy/appearance", methods={"GET"})
*/
public function getAllProductsOrderByAppearance($locale, Request $request, $noJSON = false) {
$products = [];
foreach ($this->localeService->getAllEntitiesTranslated(Product::class, $locale) as $product) {
if($product->getActif() && $product->getCollection()->getActif())
$products[] = $product;
}
$this->setAttachmentUrls($products, $this->filePathAndUrlService);
usort($products, function($a, $b) {
return $a->getOrderAppearance() - $b->getOrderAppearance();
});
if ($noJSON)
return $products;
return $this->sendResponse(['products' => $products]);
}
/**
* @Route("/{locale}/products", methods={"GET"})
*/
public function getAllProducts($locale, $noJSON = false) {
$products = [];
foreach ($this->localeService->getAllEntitiesTranslated(Product::class, $locale) as $product) {
if($product->getActif() && $product->getCollection()->getActif())
$products[] = $product;
}
$this->setAttachmentUrls($products, $this->filePathAndUrlService);
if ($noJSON)
return $products;
return $this->sendResponse(['products' => $products]);
}
/**
* @Route("/{locale}/products/orderBy/name", methods={"GET"})
*/
public function getAllProductsOrderByName($locale, Request $request, $noJSON = false) {
$products = [];
foreach ($this->localeService->getAllEntitiesTranslated(Product::class, $locale) as $product) {
if($product->getActif() && $product->getCollection()->getActif())
$products[] = $product;
}
$this->setAttachmentUrls($products, $this->filePathAndUrlService);
if ($noJSON)
return $products;
return $this->sendResponse(['products' => $products]);
}
/**
* @Route("/{locale}/collections/orderBy/appearance", methods={"GET"})
*/
public function getAllCollectionsOrderByAppearance($locale, $noJSON = false) {
$collections = [];
foreach ($this->localeService->getAllEntitiesTranslated(Collection::class, $locale) as $collection) {
if ($collection->getActif())
$collections[] = $collection;
}
$this->setAttachmentUrls($collections, $this->filePathAndUrlService);
usort($collections, function($a, $b) {
return $a->getOrderAppearance() - $b->getOrderAppearance();
});
if ($noJSON)
return $collections;
return $this->sendResponse(['collections' => $collections]);
}
/**
* @Route("/{locale}/collections", methods={"GET"})
*/
public function getAllCollections($locale, $noJSON = false) {
$collections = [];
foreach ($this->localeService->getAllEntitiesTranslated(Collection::class, $locale) as $collection) {
if ($collection->getActif())
$collections[] = $collection;
}
$this->setAttachmentUrls($collections, $this->filePathAndUrlService);
if ($noJSON)
return $collections;
return $this->sendResponse(['collections' => $collections]);
}
/**
* @Route("/{locale}/collections/orderBy/name", methods={"GET"})
*/
public function getAllCollectionsOrderByName($locale, $noJSON = false) {
$collections = [];
foreach ($this->localeService->getAllEntitiesTranslated(Collection::class, $locale) as $collection) {
if ($collection->getActif())
$collections[] = $collection;
}
$this->setAttachmentUrls($collections, $this->filePathAndUrlService);
if ($noJSON)
return $collections;
return $this->sendResponse(['collections' => $collections]);
}
/**
* @Route("/{locale}/kindProjects", methods={"GET"})
*/
public function getAllKindProjects($locale, $noJSON = false) {
$kindProjects = $this->localeService->getAllEntitiesTranslated(KindProject::class, $locale);
usort($kindProjects, function($a, $b) {
return strcmp($a->getName(), $b->getName());
});
if ($noJSON)
return $kindProjects;
return $this->sendResponse(['kindProjects' => $kindProjects]);
}
public function sendResponse($array) {
return new JsonResponse(
$array
, Response::HTTP_OK);
}
/**
* @Route("/{locale}/sections", methods={"GET"})
* @param $locale
* @param bool $noJSON
* @return array|JsonResponse
*/
public function getAllSections($locale, $noJSON = false)
{
$sections = $this->localeService->getAllEntitiesTranslated(Section::class, $locale);
usort($sections, function ($a, $b) {
return strcmp($a->getId(), $b->getId());
});
if ($noJSON)
return $sections;
return $this->sendResponse(['sections' => $sections]);
}
/**
* @Route("/{locale}/sections", methods={"GET"})
*/
public function getAllSectionsOrderByID($locale, $noJSON = false)
{
$sections = $this->localeService->getAllEntitiesTranslated(Section::class, $locale, true);
if ($noJSON)
return $sections;
return $this->sendResponse(['sections' => $sections]);
}
/**
* @Route("/{locale}/search", methods={"GET","POST"})
*/
public function search($locale, Request $request, SearchService $searchService, $noJSON = false) {
$search = json_decode($request->getContent());
if (strlen($search->search) < 4)
return new JsonResponse(null, 401);
$words = explode(' ', strtolower($search->search));
if ($noJSON)
return $searchService->search($words, $locale);
return new JsonResponse($searchService->search($words, $locale));
}
/**
* @Route("/lastAttachment", methods={"GET"})
*/
public function getLastAttachment() {
$result = $this->getDoctrine()->getManager()->createQueryBuilder()->select('a.id')->from('App\\Entity\\Attachment', 'a')->orderBy('a.id', 'DESC')->setMaxResults(1)->getQuery()->getOneOrNullResult();
return new JsonResponse(
['attachmentId' => ($result['id'] + 1)]
);
}
/**
* @Route("/getAttachments", methods={"GET"})
*/
public function getAttachments(Request $request) {
$type = $request->get('type');
$id = $request->get('id');
if(!$id)
return new JsonResponse(['attachments' => []]);
$obj = $this->getDoctrine()->getRepository("App\Entity\\".$type)->find($id);
$attachments = $obj->getAttachments()->getValues();
$this->localeService->getAllTranslationsFromEntities($attachments);
return new JsonResponse(['attachments' => $attachments]);
}
/**
* @Route("/submitNewsletter/{email}", methods={"GET"})
*/
public function submitNewsletter($email, Request $request, ValidatorInterface $validator) {
$emailConstraint = new ConstraintEmail();
$emailConstraint->message = 'Please enter a valid email';
$errors = $validator->validate($email, $emailConstraint);
if ($errors->count() > 0)
return new JsonResponse([
'error' => $errors
], 400);
$user = new User();
$user->setEmail($email);
$user->setFirstName('Newsletter');
$user->setLastName('Newsletter');
$this->getDoctrine()->getManager()->persist($user);
$this->getDoctrine()->getManager()->flush();
$newsletter = new Newsletter($user, $request->getLocale());
$this->getDoctrine()->getManager()->persist($newsletter);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse(compact('email'));
}
}