Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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 Lc\ShopBundle\Context\MerchantUtilsInterface;
  7. use Lc\ShopBundle\Context\PageInterface;
  8. use Lc\ShopBundle\Context\PointSaleInterface;
  9. use Lc\ShopBundle\Context\ReminderInterface;
  10. use Lc\ShopBundle\Context\TaxRateInterface;
  11. use Lc\ShopBundle\Context\UnitInterface;
  12. use Lc\ShopBundle\Context\UserInterface;
  13. use Lc\ShopBundle\Context\UserPointSaleInterface;
  14. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  15. use Symfony\Component\HttpFoundation\ParameterBag;
  16. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  17. use Symfony\Contracts\Translation\TranslatorInterface;
  18. class Utils
  19. {
  20. protected $em ;
  21. protected $parameterBag ;
  22. protected $merchantUtils ;
  23. protected $session;
  24. protected $translator;
  25. protected $configManager;
  26. const MEAN_PAYMENT_CREDIT_CARD = 'cb' ;
  27. const MEAN_PAYMENT_CHEQUE = 'cheque' ;
  28. const MEAN_PAYMENT_CREDIT = 'credit' ;
  29. const MEAN_PAYMENT_TRANSFER = 'transfer' ;
  30. const MEAN_PAYMENT_CASH = 'cash' ;
  31. public function __construct(EntityManagerInterface $em, ParameterBagInterface $parameterBag, SessionInterface $session, TranslatorInterface $translator, ConfigManager $configManager)
  32. {
  33. $this->em = $em ;
  34. $this->parameterBag = $parameterBag ;
  35. $this->session = $session;
  36. $this->translator = $translator;
  37. $this->configManager = $configManager;
  38. }
  39. public function getElementByDevAlias($devAlias, $class = PageInterface::class)
  40. {
  41. $class = $this->em->getClassMetadata($class)->getName();
  42. return $this->em->getRepository($class)->findOneByDevAlias($devAlias) ;
  43. }
  44. public function isServerLocalhost()
  45. {
  46. return in_array($_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1']) ;
  47. }
  48. public function getCookieDomain()
  49. {
  50. return ($this->isServerLocalhost()) ? null : $this->parameterBag->get('app.cookie_domain_distant') ;
  51. }
  52. public function limitText($text, $limit) {
  53. $text = strip_tags($text) ;
  54. if (str_word_count($text, 0) > $limit) {
  55. $words = str_word_count($text, 2);
  56. $pos = array_keys($words);
  57. $text = substr($text, 0, $pos[$limit]) . '...';
  58. }
  59. return $text;
  60. }
  61. function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true) {
  62. if ($considerHtml) {
  63. // if the plain text is shorter than the maximum length, return the whole text
  64. if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
  65. return $text;
  66. }
  67. // splits all html-tags to scanable lines
  68. preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
  69. $total_length = strlen($ending);
  70. $open_tags = array();
  71. $truncate = '';
  72. foreach ($lines as $line_matchings) {
  73. // if there is any html-tag in this line, handle it and add it (uncounted) to the output
  74. if (!empty($line_matchings[1])) {
  75. // if it's an "empty element" with or without xhtml-conform closing slash
  76. if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
  77. // do nothing
  78. // if tag is a closing tag
  79. } else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
  80. // delete tag from $open_tags list
  81. $pos = array_search($tag_matchings[1], $open_tags);
  82. if ($pos !== false) {
  83. unset($open_tags[$pos]);
  84. }
  85. // if tag is an opening tag
  86. } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
  87. // add tag to the beginning of $open_tags list
  88. array_unshift($open_tags, strtolower($tag_matchings[1]));
  89. }
  90. // add html-tag to $truncate'd text
  91. $truncate .= $line_matchings[1];
  92. }
  93. // calculate the length of the plain text part of the line; handle entities as one character
  94. $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
  95. if ($total_length+$content_length> $length) {
  96. // the number of characters which are left
  97. $left = $length - $total_length;
  98. $entities_length = 0;
  99. // search for html entities
  100. 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)) {
  101. // calculate the real length of all entities in the legal range
  102. foreach ($entities[0] as $entity) {
  103. if ($entity[1]+1-$entities_length <= $left) {
  104. $left--;
  105. $entities_length += strlen($entity[0]);
  106. } else {
  107. // no more characters left
  108. break;
  109. }
  110. }
  111. }
  112. $truncate .= substr($line_matchings[2], 0, $left+$entities_length);
  113. // maximum lenght is reached, so get off the loop
  114. break;
  115. } else {
  116. $truncate .= $line_matchings[2];
  117. $total_length += $content_length;
  118. }
  119. // if the maximum length is reached, get off the loop
  120. if($total_length>= $length) {
  121. break;
  122. }
  123. }
  124. } else {
  125. if (strlen($text) <= $length) {
  126. return $text;
  127. } else {
  128. $truncate = substr($text, 0, $length - strlen($ending));
  129. }
  130. }
  131. // if the words shouldn't be cut in the middle...
  132. if (!$exact) {
  133. // ...search the last occurance of a space...
  134. $spacepos = strrpos($truncate, ' ');
  135. if (isset($spacepos)) {
  136. // ...and cut the text in this position
  137. $truncate = substr($truncate, 0, $spacepos);
  138. }
  139. }
  140. // add the defined ending to the text
  141. $truncate .= $ending;
  142. if($considerHtml) {
  143. // close all unclosed html-tags
  144. foreach ($open_tags as $tag) {
  145. $truncate .= '</' . $tag . '>';
  146. }
  147. }
  148. return $truncate;
  149. }
  150. public function isBot()
  151. {
  152. if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|crawl|slurp|spider/i', $_SERVER['HTTP_USER_AGENT'])) {
  153. return TRUE;
  154. } else {
  155. return FALSE;
  156. }
  157. }
  158. public function slugify($string)
  159. {
  160. $slugify = new Slugify();
  161. return $slugify->slugify($string) ;
  162. }
  163. public function getUnitsList()
  164. {
  165. $unitsList =array();
  166. $units = $this->em->getRepository(UnitInterface::class)->findAll();
  167. foreach ($units as $unit){
  168. $unitsList[$unit->getId()]['unit'] = $unit->getUnit();
  169. $unitsList[$unit->getId()]['wordingUnit'] = $unit->getWordingUnit();
  170. $unitsList[$unit->getId()]['wording'] = $unit->getWording();
  171. $unitsList[$unit->getId()]['wordingShort'] = $unit->getWordingShort();
  172. $unitsList[$unit->getId()]['coefficient'] = $unit->getCoefficient();
  173. $unitsList[$unit->getId()]['unitReference'] = $unit->getUnitReference()->getId();
  174. }
  175. return $unitsList;
  176. }
  177. public function isUserLinkedToPointSale(UserInterface $user, PointSaleInterface $pointSale)
  178. {
  179. foreach($user->getUserPointSales() as $userPointSale) {
  180. if($userPointSale->getPointSale()->getId() == $pointSale->getId()) {
  181. return true ;
  182. }
  183. }
  184. return false ;
  185. }
  186. public function linkUserToPointSale(UserInterface $user, PointSaleInterface $pointSale)
  187. {
  188. if(!$this->isUserLinkedToPointSale($user, $pointSale)) {
  189. $userPointSaleClass = $this->em->getClassMetadata(UserPointSaleInterface::class)->getName();
  190. $userPointSale = new $userPointSaleClass ;
  191. $userPointSale->setUser($user) ;
  192. $userPointSale->setPointSale($pointSale) ;
  193. $this->em->persist($userPointSale);
  194. $this->em->flush() ;
  195. }
  196. }
  197. function callCitiesApi($method, $url, $data = false)
  198. {
  199. $url = 'https://geo.api.gouv.fr/'.$url ;
  200. $curl = curl_init();
  201. switch ($method)
  202. {
  203. case "POST":
  204. curl_setopt($curl, CURLOPT_POST, 1);
  205. if ($data)
  206. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  207. break;
  208. case "PUT":
  209. curl_setopt($curl, CURLOPT_PUT, 1);
  210. break;
  211. default:
  212. if ($data)
  213. $url = sprintf("%s?%s", $url, http_build_query($data));
  214. }
  215. // Optional Authentication:
  216. curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  217. curl_setopt($curl, CURLOPT_USERPWD, "username:password");
  218. curl_setopt($curl, CURLOPT_URL, $url);
  219. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  220. $result = curl_exec($curl);
  221. curl_close($curl);
  222. return $result;
  223. }
  224. public function getZipByCity($city, $code = null)
  225. {
  226. $zip = null ;
  227. $paramsSearch = [
  228. 'nom' => $city,
  229. 'fields' => 'nom,codesPostaux'
  230. ] ;
  231. if($code != null && $code != 0) {
  232. $paramsSearch['code'] = $code ;
  233. }
  234. $returnCitiesSearchZip = json_decode($this->callCitiesApi('get', 'communes', $paramsSearch)) ;
  235. if($returnCitiesSearchZip) {
  236. foreach($returnCitiesSearchZip as $citySearchZip) {
  237. if(strtolower(trim($city)) == strtolower(trim($citySearchZip->nom))) {
  238. $zip = $citySearchZip->codesPostaux[0] ;
  239. }
  240. }
  241. }
  242. return $zip ;
  243. }
  244. public function date($format, $timestamp)
  245. {
  246. setlocale(LC_TIME, 'fr_FR.UTF8', 'fr.UTF8', 'fr_FR.UTF-8', 'fr.UTF-8');
  247. return strftime($format, $timestamp) ;
  248. }
  249. public function getNextDay($day)
  250. {
  251. return new \DateTime('next '.$day) ;
  252. }
  253. public function getNextDayByNumber($number)
  254. {
  255. return $this->getNextDay($this->getDayByNumber($number, 'en')) ;
  256. }
  257. public function getDayByNumber($number, $lang = 'fr')
  258. {
  259. if($lang == 'fr') {
  260. $daysArray = [
  261. 1 => 'Lundi',
  262. 2 => 'Mardi',
  263. 3 => 'Mercredi',
  264. 4 => 'Jeudi',
  265. 5 => 'Vendredi',
  266. 6 => 'Samedi',
  267. 7 => 'Dimanche'
  268. ] ;
  269. }
  270. else {
  271. $daysArray = [
  272. 1 => 'Monday',
  273. 2 => 'Tuesday',
  274. 3 => 'Wednesday',
  275. 4 => 'Thursday',
  276. 5 => 'Friday',
  277. 6 => 'Saturday',
  278. 7 => 'Sunday',
  279. ] ;
  280. }
  281. if(isset($daysArray[$number])) {
  282. return $daysArray[$number] ;
  283. }
  284. return '' ;
  285. }
  286. public function addFlash($success, $message, $extraMessages = array(), $params=array(), $domain='lcshop'){
  287. $message = $this->translator->trans($message, $params,$domain);
  288. if (count($extraMessages)) {
  289. $message .= '<ul>';
  290. foreach ($extraMessages as $extraMessage) {
  291. $message .= '<li> <i>' . $this->translator->trans($extraMessage, array(), $domain) . '</i></li>';
  292. }
  293. $message .= '</ul>';
  294. }
  295. $this->session->getFlashBag()->add($success, $message);
  296. }
  297. public function getFlashMessages(){
  298. return $this->session->getFlashBag()->all();
  299. }
  300. function camelCase($str) {
  301. $i = array("-","_");
  302. $str = preg_replace('/([a-z])([A-Z])/', "\\1 \\2", $str);
  303. $str = preg_replace('@[^a-zA-Z0-9\-_ ]+@', '', $str);
  304. $str = str_replace($i, ' ', $str);
  305. $str = str_replace(' ', '', ucwords(strtolower($str)));
  306. $str = strtolower(substr($str,0,1)).substr($str,1);
  307. return $str;
  308. }
  309. function snakeCase($str) {
  310. $str = preg_replace('/([a-z])([A-Z])/', "\\1_\\2", $str);
  311. $str = strtolower($str);
  312. return $str;
  313. }
  314. public function csvEscape($str){
  315. return str_replace(array("\r", "\n"), ' ', $str);
  316. }
  317. public function getRemindersByUser($user)
  318. {
  319. $reminderRepo = $this->em->getRepository(ReminderInterface::class);
  320. $reminders = $reminderRepo->findByUser($user);
  321. $entitiesRepo = array();
  322. $entitiesConfig = array();
  323. if(count($reminders)>0 ) {
  324. foreach ($reminders as $reminder) {
  325. if($reminder->getEntityName()) {
  326. if (!isset($entitiesConfig[$reminder->getEntityName()])) {
  327. $entitiesConfig[$reminder->getEntityName()] = $this->configManager->getEntityConfig($reminder->getEntityName());
  328. }
  329. if($reminder->getEntityAction() == 'edit' || $reminder->getEntityAction() == 'show') {
  330. if (!isset($entitiesRepo[$reminder->getEntityName()])) {
  331. $entitiesRepo[$reminder->getEntityName()] = $this->em->getRepository($entitiesConfig[$reminder->getEntityName()]['class']);
  332. }
  333. if($reminder->getEntityId()) {
  334. $reminder->relatedPage = $entitiesRepo[$reminder->getEntityName()]->find($reminder->getEntityId())->__toString();
  335. }
  336. } else {
  337. $reminder->relatedPage = 'Liste de ' . $entitiesConfig[$reminder->getEntityName()]['label'];
  338. }
  339. }
  340. }
  341. }
  342. return $reminders;
  343. }
  344. }