src/Services/Common/TextTools.php line 18

Open in your IDE?
  1. <?php
  2. //----------------------------------------------------------------------
  3. // src/Services/Common/TextTools.php
  4. //----------------------------------------------------------------------
  5. namespace App\Services\Common;
  6. use Doctrine\Persistence\ManagerRegistry;
  7. use App\Entity\SocietyGroup;
  8. use App\Entity\Client\Zone;
  9. use App\Services\LogTools;
  10. class TextTools
  11. {
  12.     public function __construct(ManagerRegistry $doctrine, LogTools $logTools)
  13.     {
  14.         $this->em = $doctrine->getManager();
  15.         $this->logTools = $logTools;
  16.     }
  17.     public function formatIkeaBpObjectLogs($text)
  18.     {
  19.         $text = str_replace("\t\t\t", "<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", $text);
  20.         $text = str_replace("\t\t", "<br><br>&nbsp;&nbsp;&nbsp;", $text);
  21.         $text = str_replace("\t", "<br><br>", $text);
  22.         return $text;
  23.     }
  24.     // Mainly used by Sms
  25.     public function removeInsecableSpace($text)
  26.     {
  27.         // Need to transform in html to replace &nbsp; space and transform it again in a plain text
  28.         $text = htmlentities($text);
  29.         $textWithoutInsecableSpace = str_replace('&nbsp;',' ',$text);
  30.         $text = html_entity_decode($textWithoutInsecableSpace);
  31.         return $text;
  32.     }
  33.     public function generateAlphaChars($length = 16)
  34.     {
  35.         $charAllowed = "abcdefghijqlmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVXYZ";
  36.         $sizeCharAllowed = mb_strlen($charAllowed);
  37.         $chars = "";
  38.         for ($i = 0; $i < $length; $i++)
  39.         {
  40.             $letterIndex = random_int(0, $sizeCharAllowed-1);
  41.             $chars .= $charAllowed[$letterIndex];
  42.         }
  43.         return $chars;
  44.     }
  45.     public function encodeForJson($value)
  46.     {
  47.         if ($value === null)
  48.             return "null";
  49.         if ($value == 0)
  50.             return "0";
  51.         return $value;
  52.     }
  53.     public function arrayToString($minions)
  54.     {
  55.         if (count($minions) < 1)
  56.             return "(0)";
  57.         $ids = "";
  58.         foreach ($minions as $minion)
  59.         {
  60.             $ids .= $minion->getId();
  61.             $ids .= ",";
  62.         }
  63.         $ids = substr($ids, 0, -1);
  64.         $ids = "(".$ids.")";
  65.         return $ids;
  66.     }
  67.     public function arrayToStringDisplay($minions)
  68.     {
  69.         if (count($minions) < 1)
  70.             return "";
  71.         $output = "";
  72.         foreach ($minions as $minion)
  73.         {
  74.             $output .= $minion;
  75.             $output .= ", ";
  76.         }
  77.         $output = substr($output, 0, -1);
  78.         $output = substr($output, 0, -1);
  79.         return $output;
  80.     }
  81.     public function camelToSnakeCase($text)
  82.     {
  83.         // preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $text, $matches);
  84.         // $ret = $matches[0];
  85.         // foreach ($ret as &$match)
  86.         // {
  87.         //     $match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
  88.         // }
  89.         // return implode('_', $ret);
  90.         return strtolower(preg_replace(['/([a-z\d])([A-Z])/', '/([^_])([A-Z][a-z])/'], '$1_$2', $text));
  91.     }
  92.     public function cleanTextWithoutHtmlentities($text, $removeEOL = 1)
  93.     {
  94.         // Plan.io Task #3953
  95.         if (empty($text)) return $text;
  96.         // Plan.io Task #4670 — branch rekapp_remix
  97.         // str_replace() maps over arrays without complaining, so a non-string only blows up
  98.         // further down on trim(). Encode it here instead: callers store the result in a text
  99.         // column and an internal defect must not turn into an uncaught TypeError.
  100.         $text = $this->forceString($text);
  101.         $text = str_replace('"', "'", $text);
  102.         $text = str_replace('œ', 'oe', $text);
  103.         $text = str_replace('’', "'", $text);
  104.         $text = preg_replace('/[\t]/', ' ', trim($text));
  105.         if($removeEOL == 1)
  106.         {
  107.             $text = str_replace(array("\r\n", "\n", "\r"), ' ', $text);
  108.         }
  109.         else if($removeEOL == 2)
  110.         {
  111.             $text = str_replace(array("\r\n", "\n", "\r"), '<br>', $text);
  112.         }
  113.         return $text;
  114.     }
  115.     public function cleanText($text, $removeEOL = 1)
  116.     {
  117.         // Plan.io Task #3953
  118.         if (empty($text)) return $text;
  119.         $text = str_replace('"', "'", $text);
  120.         $text = str_replace('œ', 'oe', $text);
  121.         $text = str_replace('’', "'", $text);
  122.         $text = preg_replace('/[\t]/', ' ', trim($text));
  123.         if($removeEOL == 1)
  124.         {
  125.             $text = str_replace(array("\r\n", "\n", "\r"), ' ', $text);
  126.         }
  127.         else if($removeEOL == 2)
  128.         {
  129.             $text = str_replace(array("\r\n", "\n", "\r"), '<br>', $text);
  130.         }
  131.         return htmlentities($text);
  132.     }
  133.     public function strtoupperFr($string)
  134.     {
  135.         // Plan.io Task #3953
  136.         if (empty($string)) return $string;
  137.         $string = strtoupper($string);
  138.         $string = str_replace(
  139.             array('é', 'è', 'ê', 'ë', 'à', 'â', 'î', 'ï', 'ô', 'ù', 'û'),
  140.             array('É', 'È', 'Ê', 'Ë', 'À', 'Â', 'Î', 'Ï', 'Ô', 'Ù', 'Û'),
  141.             $string
  142.         );
  143.         return $string;
  144.     }
  145.     public function removeWhitespaces($string)
  146.     {
  147.         // Plan.io Task #3953
  148.         if (empty($string)) return $string;
  149.         $string = preg_replace('/\s+/', '', $string);
  150.         return $string;
  151.     }
  152.     public function cropText($text, $maxNbChar)
  153.     {
  154.         // Plan.io Task #3953
  155.         if (empty($text)) return $text;
  156.         // If title si too long, crop it
  157.         if(strlen($text) > $maxNbChar-3)
  158.         {
  159.             return mb_substr($text,0,$maxNbChar, 'UTF-8') . "...";
  160.         }
  161.         return $text;
  162.     }
  163.     public function encode_utf8($string, $encode = null)
  164.     {
  165.         $fromEncoding = mb_detect_encoding($string);
  166.         if ($fromEncoding === false)
  167.         {
  168.             return $string;
  169.         }
  170.         if ($encode === null)
  171.         {
  172.             $encode = 'UTF-8';
  173.         }
  174.         try
  175.         {
  176.             $stringEncoded = mb_convert_encoding($string, $encode, $fromEncoding);
  177.         }
  178.         catch(\Exception $e)
  179.         {
  180.             return $string;
  181.         }
  182.         if ($stringEncoded === false)
  183.         {
  184.             return $string;
  185.         }
  186.         return $stringEncoded;
  187.     }
  188.     public function removeNonAlphaNumeric($string)
  189.     {
  190.         $string = preg_replace('/[^a-z\d ]/i', '', $string);
  191.         return $string;
  192.     }
  193.     public function craftSimpleNameForZone(SocietyGroup $societyGroup, Zone $zone)
  194.     {
  195.         $display = $this->removeNonAlphaNumeric($societyGroup->getRef());
  196.         $display = $this->camelToSnakeCase($display);
  197.         $societyGroupDisplay = $societyGroup->getId()."_".$display;
  198.         $display = $zone->getDisplay();
  199.         $display = $this->removeNonAlphaNumeric($display);
  200.         $display = $this->camelToSnakeCase($display);
  201.         $zoneDisplay = $zone->getId()."_".$display;
  202.         return $societyGroupDisplay."_".$zoneDisplay;
  203.     }
  204.     public function toUpperASCII( $str )
  205.     {
  206.         return strtoupper(strtr(utf8_decode($str),
  207.             utf8_decode(
  208.             'ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ'),
  209.             'SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy'));
  210.     }
  211.     public function parseEmailConfigData($string)
  212.     {
  213.         $string = preg_replace('/[^a-z_]/', '', $string);
  214.         return $string;
  215.     }
  216.     /**
  217.      * Coerces any value into a string so the cleaning helpers never hit a TypeError.
  218.      *
  219.      * Arrays and objects (json columns, DTOs) are encoded, scalars are cast. Whoever passed a
  220.      * non-string is the actual bug — this only keeps a logging concern from aborting the
  221.      * request that triggered it.
  222.      *
  223.      * Plan.io Task #4670 — branch rekapp_remix
  224.      *
  225.      * @param mixed $value
  226.      */
  227.     private function forceString($value): string
  228.     {
  229.         if (is_string($value))
  230.         {
  231.             return $value;
  232.         }
  233.         if (is_array($value) || $value instanceof \JsonSerializable || $value instanceof \stdClass)
  234.         {
  235.             $encoded = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  236.             return $encoded === false ? '' : $encoded;
  237.         }
  238.         // Objects exposing __toString(), int, float, bool.
  239.         if (is_scalar($value) || (is_object($value) && method_exists($value, '__toString')))
  240.         {
  241.             return (string) $value;
  242.         }
  243.         $this->logTools->errorlog('[TextTools][forceString] unsupported type '.gettype($value));
  244.         return '';
  245.     }
  246. }