You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Utils.php 22KB

4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. <?php
  2. namespace Lc\ShopBundle\Services;
  3. use Cocur\Slugify\Slugify;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use EasyCorp\Bundle\EasyAdminBundle\Configuration\ConfigManager;
  6. use Geocoder\Model\Coordinates;
  7. use Geocoder\Provider\Addok\Addok;
  8. use Geocoder\Query\GeocodeQuery;
  9. use Geocoder\Query\ReverseQuery;
  10. use Lc\ShopBundle\Context\ImageInterface;
  11. use Lc\ShopBundle\Context\MerchantUtilsInterface;
  12. use Lc\ShopBundle\Context\PageInterface;
  13. use Lc\ShopBundle\Context\PointSaleInterface;
  14. use Lc\ShopBundle\Context\ProductFamilyInterface;
  15. use Lc\ShopBundle\Context\ProductFamilyUtilsInterface;
  16. use Lc\ShopBundle\Context\ReminderInterface;
  17. use Lc\ShopBundle\Context\TaxRateInterface;
  18. use Lc\ShopBundle\Context\UnitInterface;
  19. use Lc\ShopBundle\Context\UserInterface;
  20. use Lc\ShopBundle\Context\UserPointSaleInterface;
  21. use Liip\ImagineBundle\Imagine\Cache\CacheManager;
  22. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  23. use Symfony\Component\HttpClient\HttplugClient;
  24. use Symfony\Component\HttpFoundation\ParameterBag;
  25. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  26. use Symfony\Contracts\Translation\TranslatorInterface;
  27. class Utils
  28. {
  29. protected $em;
  30. protected $parameterBag;
  31. protected $merchantUtils;
  32. protected $session;
  33. protected $translator;
  34. protected $configManager;
  35. const MEAN_PAYMENT_CREDIT_CARD = 'cb';
  36. const MEAN_PAYMENT_CHEQUE = 'cheque';
  37. const MEAN_PAYMENT_CREDIT = 'credit';
  38. const MEAN_PAYMENT_TRANSFER = 'transfer';
  39. const MEAN_PAYMENT_CASH = 'cash';
  40. public function __construct(EntityManagerInterface $em, ParameterBagInterface $parameterBag, SessionInterface $session, TranslatorInterface $translator, ConfigManager $configManager, CacheManager $liipCacheHelper)
  41. {
  42. $this->em = $em;
  43. $this->parameterBag = $parameterBag;
  44. $this->session = $session;
  45. $this->translator = $translator;
  46. $this->configManager = $configManager;
  47. $this->liipCacheHelper = $liipCacheHelper;
  48. }
  49. public function getElementByDevAlias($devAlias, $class = PageInterface::class)
  50. {
  51. $class = $this->em->getClassMetadata($class)->getName();
  52. return $this->em->getRepository($class)->findOneByDevAlias($devAlias);
  53. }
  54. public function isServerLocalhost()
  55. {
  56. return in_array($_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1']);
  57. }
  58. public function getCookieDomain()
  59. {
  60. return ($this->isServerLocalhost()) ? null : $this->parameterBag->get('app.cookie_domain_distant');
  61. }
  62. public function limitText($text, $limit)
  63. {
  64. $text = strip_tags($text);
  65. if (str_word_count($text, 0) > $limit) {
  66. $words = str_word_count($text, 2);
  67. $pos = array_keys($words);
  68. $text = substr($text, 0, $pos[$limit]) . '...';
  69. }
  70. return $text;
  71. }
  72. function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true)
  73. {
  74. if ($considerHtml) {
  75. // if the plain text is shorter than the maximum length, return the whole text
  76. if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
  77. return $text;
  78. }
  79. // splits all html-tags to scanable lines
  80. preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
  81. $total_length = strlen($ending);
  82. $open_tags = array();
  83. $truncate = '';
  84. foreach ($lines as $line_matchings) {
  85. // if there is any html-tag in this line, handle it and add it (uncounted) to the output
  86. if (!empty($line_matchings[1])) {
  87. // if it's an "empty element" with or without xhtml-conform closing slash
  88. if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
  89. // do nothing
  90. // if tag is a closing tag
  91. } else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
  92. // delete tag from $open_tags list
  93. $pos = array_search($tag_matchings[1], $open_tags);
  94. if ($pos !== false) {
  95. unset($open_tags[$pos]);
  96. }
  97. // if tag is an opening tag
  98. } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
  99. // add tag to the beginning of $open_tags list
  100. array_unshift($open_tags, strtolower($tag_matchings[1]));
  101. }
  102. // add html-tag to $truncate'd text
  103. $truncate .= $line_matchings[1];
  104. }
  105. // calculate the length of the plain text part of the line; handle entities as one character
  106. $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
  107. if ($total_length + $content_length > $length) {
  108. // the number of characters which are left
  109. $left = $length - $total_length;
  110. $entities_length = 0;
  111. // search for html entities
  112. if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
  113. // calculate the real length of all entities in the legal range
  114. foreach ($entities[0] as $entity) {
  115. if ($entity[1] + 1 - $entities_length <= $left) {
  116. $left--;
  117. $entities_length += strlen($entity[0]);
  118. } else {
  119. // no more characters left
  120. break;
  121. }
  122. }
  123. }
  124. $truncate .= substr($line_matchings[2], 0, $left + $entities_length);
  125. // maximum lenght is reached, so get off the loop
  126. break;
  127. } else {
  128. $truncate .= $line_matchings[2];
  129. $total_length += $content_length;
  130. }
  131. // if the maximum length is reached, get off the loop
  132. if ($total_length >= $length) {
  133. break;
  134. }
  135. }
  136. } else {
  137. if (strlen($text) <= $length) {
  138. return $text;
  139. } else {
  140. $truncate = substr($text, 0, $length - strlen($ending));
  141. }
  142. }
  143. // if the words shouldn't be cut in the middle...
  144. if (!$exact) {
  145. // ...search the last occurance of a space...
  146. $spacepos = strrpos($truncate, ' ');
  147. if (isset($spacepos)) {
  148. // ...and cut the text in this position
  149. $truncate = substr($truncate, 0, $spacepos);
  150. }
  151. }
  152. // add the defined ending to the text
  153. $truncate .= $ending;
  154. if ($considerHtml) {
  155. // close all unclosed html-tags
  156. foreach ($open_tags as $tag) {
  157. $truncate .= '</' . $tag . '>';
  158. }
  159. }
  160. return $truncate;
  161. }
  162. public function isBot()
  163. {
  164. if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|crawl|slurp|spider/i', $_SERVER['HTTP_USER_AGENT'])) {
  165. return TRUE;
  166. } else {
  167. return FALSE;
  168. }
  169. }
  170. public function slugify($string)
  171. {
  172. $slugify = new Slugify();
  173. return $slugify->slugify($string);
  174. }
  175. public function getUnitsList()
  176. {
  177. $unitsList = array();
  178. $units = $this->em->getRepository(UnitInterface::class)->findAll();
  179. foreach ($units as $unit) {
  180. $unitsList[$unit->getId()]['unit'] = $unit->getUnit();
  181. $unitsList[$unit->getId()]['wordingUnit'] = $unit->getWordingUnit();
  182. $unitsList[$unit->getId()]['wording'] = $unit->getWording();
  183. $unitsList[$unit->getId()]['wordingShort'] = $unit->getWordingShort();
  184. $unitsList[$unit->getId()]['coefficient'] = $unit->getCoefficient();
  185. $unitsList[$unit->getId()]['unitReference'] = $unit->getUnitReference()->getId();
  186. }
  187. return $unitsList;
  188. }
  189. public function isUserLinkedToPointSale(UserInterface $user, PointSaleInterface $pointSale)
  190. {
  191. foreach ($user->getUserPointSales() as $userPointSale) {
  192. if ($userPointSale->getPointSale()->getId() == $pointSale->getId()) {
  193. return true;
  194. }
  195. }
  196. return false;
  197. }
  198. public function linkUserToPointSale(UserInterface $user, PointSaleInterface $pointSale)
  199. {
  200. if (!$this->isUserLinkedToPointSale($user, $pointSale)) {
  201. $userPointSaleClass = $this->em->getClassMetadata(UserPointSaleInterface::class)->getName();
  202. $userPointSale = new $userPointSaleClass;
  203. $userPointSale->setUser($user);
  204. $userPointSale->setPointSale($pointSale);
  205. $this->em->persist($userPointSale);
  206. $this->em->flush();
  207. }
  208. }
  209. function callCitiesApi($method, $url, $data = false)
  210. {
  211. $url = 'https://geo.api.gouv.fr/' . $url;
  212. $curl = curl_init();
  213. switch ($method) {
  214. case "POST":
  215. curl_setopt($curl, CURLOPT_POST, 1);
  216. if ($data)
  217. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  218. break;
  219. case "PUT":
  220. curl_setopt($curl, CURLOPT_PUT, 1);
  221. break;
  222. default:
  223. if ($data)
  224. $url = sprintf("%s?%s", $url, http_build_query($data));
  225. }
  226. // Optional Authentication:
  227. curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  228. curl_setopt($curl, CURLOPT_USERPWD, "username:password");
  229. curl_setopt($curl, CURLOPT_URL, $url);
  230. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  231. $result = curl_exec($curl);
  232. curl_close($curl);
  233. return $result;
  234. }
  235. public function getGeocoderProvider()
  236. {
  237. $symfonyClient = new HttplugClient();
  238. $provider = new Addok($symfonyClient, 'https://api-adresse.data.gouv.fr') ;
  239. return $provider ;
  240. }
  241. public function callAddressApi($query)
  242. {
  243. $provider = $this->getGeocoderProvider() ;;
  244. $query = GeocodeQuery::create($query)->withData('type', 'housenumber');
  245. $results = $provider->geocodeQuery($query);
  246. return $results->all() ;
  247. }
  248. public function callReverseAddressApi($latitude, $longitude)
  249. {
  250. $provider = $this->getGeocoderProvider() ;;
  251. $query = ReverseQuery::create(new Coordinates($latitude, $longitude));
  252. $results = $provider->reverseQuery($query);
  253. return $results->all() ;
  254. }
  255. public function getZipByCity($city, $code = null)
  256. {
  257. $zip = null;
  258. $paramsSearch = [
  259. 'nom' => $city,
  260. 'fields' => 'nom,codesPostaux'
  261. ];
  262. if ($code != null && $code != 0) {
  263. $paramsSearch['code'] = $code;
  264. }
  265. $returnCitiesSearchZip = json_decode($this->callCitiesApi('get', 'communes', $paramsSearch));
  266. if ($returnCitiesSearchZip) {
  267. foreach ($returnCitiesSearchZip as $citySearchZip) {
  268. if (strtolower(trim($city)) == strtolower(trim($citySearchZip->nom))) {
  269. $zip = $citySearchZip->codesPostaux[0];
  270. }
  271. }
  272. }
  273. return $zip;
  274. }
  275. public function date($format, $timestamp)
  276. {
  277. setlocale(LC_TIME, 'fr_FR.UTF8', 'fr.UTF8', 'fr_FR.UTF-8', 'fr.UTF-8');
  278. return strftime($format, $timestamp);
  279. }
  280. public function getNextDay($day)
  281. {
  282. return new \DateTime('next ' . $day);
  283. }
  284. public function getNextDayByNumber($number)
  285. {
  286. return $this->getNextDay($this->getDayByNumber($number, 'en'));
  287. }
  288. public function getDayByNumber($number, $lang = 'fr')
  289. {
  290. if ($lang == 'fr') {
  291. $daysArray = [
  292. 1 => 'Lundi',
  293. 2 => 'Mardi',
  294. 3 => 'Mercredi',
  295. 4 => 'Jeudi',
  296. 5 => 'Vendredi',
  297. 6 => 'Samedi',
  298. 7 => 'Dimanche'
  299. ];
  300. } else {
  301. $daysArray = [
  302. 1 => 'Monday',
  303. 2 => 'Tuesday',
  304. 3 => 'Wednesday',
  305. 4 => 'Thursday',
  306. 5 => 'Friday',
  307. 6 => 'Saturday',
  308. 7 => 'Sunday',
  309. ];
  310. }
  311. if (isset($daysArray[$number])) {
  312. return $daysArray[$number];
  313. }
  314. return '';
  315. }
  316. public function addFlash($success, $message, $extraMessages = array(), $params = array(), $domain = 'lcshop')
  317. {
  318. $message = $this->translator->trans($message, $params, $domain);
  319. if (count($extraMessages)) {
  320. $message .= '<ul>';
  321. foreach ($extraMessages as $extraMessage) {
  322. $message .= '<li> <i>' . $this->translator->trans($extraMessage, array(), $domain) . '</i></li>';
  323. }
  324. $message .= '</ul>';
  325. }
  326. $this->session->getFlashBag()->add($success, $message);
  327. }
  328. public function getFlashMessages()
  329. {
  330. return $this->session->getFlashBag()->all();
  331. }
  332. function camelCase($str)
  333. {
  334. $i = array("-", "_");
  335. $str = preg_replace('/([a-z])([A-Z])/', "\\1 \\2", $str);
  336. $str = preg_replace('@[^a-zA-Z0-9\-_ ]+@', '', $str);
  337. $str = str_replace($i, ' ', $str);
  338. $str = str_replace(' ', '', ucwords(strtolower($str)));
  339. $str = strtolower(substr($str, 0, 1)) . substr($str, 1);
  340. return $str;
  341. }
  342. function snakeCase($str)
  343. {
  344. $str = preg_replace('/([a-z])([A-Z])/', "\\1_\\2", $str);
  345. $str = strtolower($str);
  346. return $str;
  347. }
  348. public function csvEscape($str)
  349. {
  350. return str_replace(array("\r", "\n"), ' ', $str);
  351. }
  352. public function getRemindersByUser($user)
  353. {
  354. $reminderRepo = $this->em->getRepository(ReminderInterface::class);
  355. $reminders = $reminderRepo->findByUser($user);
  356. $entitiesRepo = array();
  357. $entitiesConfig = array();
  358. if (count($reminders) > 0) {
  359. foreach ($reminders as $reminder) {
  360. if ($reminder->getEntityName()) {
  361. if (!isset($entitiesConfig[$reminder->getEntityName()])) {
  362. $entitiesConfig[$reminder->getEntityName()] = $this->configManager->getEntityConfig($reminder->getEntityName());
  363. }
  364. if ($reminder->getEntityAction() == 'edit' || $reminder->getEntityAction() == 'show') {
  365. if (!isset($entitiesRepo[$reminder->getEntityName()])) {
  366. $entitiesRepo[$reminder->getEntityName()] = $this->em->getRepository($entitiesConfig[$reminder->getEntityName()]['class']);
  367. }
  368. if ($reminder->getEntityId()) {
  369. $reminder->relatedPage = $entitiesRepo[$reminder->getEntityName()]->find($reminder->getEntityId())->__toString();
  370. }
  371. } else {
  372. $reminder->relatedPage = 'Liste de ' . $entitiesConfig[$reminder->getEntityName()]['label'];
  373. }
  374. }
  375. }
  376. }
  377. return $reminders;
  378. }
  379. public function removeDir($dir)
  380. {
  381. $files = array_diff(scandir($dir), array('.', '..'));
  382. foreach ($files as $file) {
  383. (is_dir("$dir/$file")) ? $this->removeDir("$dir/$file") : unlink("$dir/$file");
  384. }
  385. return rmdir($dir);
  386. }
  387. function folderToZip($folder, &$zipFile, $subfolder = null)
  388. {
  389. if ($zipFile == null) {
  390. // no resource given, exit
  391. return false;
  392. }
  393. // we check if $folder has a slash at its end, if not, we append one
  394. $tabFolder = str_split($folder);
  395. $tabSubFolder = str_split($subfolder);
  396. $folder .= end($tabFolder) == "/" ? "" : "/";
  397. $subfolder .= end($tabSubFolder) == "/" ? "" : "/";
  398. // we start by going through all files in $folder
  399. $handle = opendir($folder);
  400. while ($f = readdir($handle)) {
  401. if ($f != "." && $f != "..") {
  402. if (is_file($folder . $f)) {
  403. // if we find a file, store it
  404. // if we have a subfolder, store it there
  405. if ($subfolder != null)
  406. $zipFile->addFile($folder . $f, $subfolder . $f);
  407. else
  408. $zipFile->addFile($folder . $f);
  409. } elseif (is_dir($folder . $f)) {
  410. // if we find a folder, create a folder in the zip
  411. $zipFile->addEmptyDir($f);
  412. // and call the function again
  413. folderToZip($folder . $f, $zipFile, $f);
  414. }
  415. }
  416. }
  417. }
  418. public function lcLiip($path, $thumb = 'tile', $default = 'default.jpg')
  419. {
  420. if (substr($path, 0, 1) === '/') $path = substr($path, 1);
  421. if ($path) {
  422. $fileManagerFolder = substr($this->getFileManagerFolder(), 1) ;
  423. if (strpos($path, $fileManagerFolder) === false) {
  424. $path = $fileManagerFolder . '/' . $path;
  425. }
  426. if (file_exists($path)) {
  427. return $this->liipCacheHelper->getBrowserPath($path, $thumb);
  428. }
  429. }
  430. return $this->liipCacheHelper->getBrowserPath($this->getFileManagerFolder() . '/' . $default, $thumb);
  431. }
  432. /**
  433. * Retourne le chemin vers le dossier d'uploads de responsiveFilemanager
  434. *
  435. * @return string
  436. */
  437. public function getFileManagerFolder()
  438. {
  439. return $this->parameterBag->get('app.path.images');
  440. }
  441. }