CRM-18199 Stripping commnt regexp
authorggargani <giovanni@gargani.it>
Fri, 16 Sep 2016 07:11:32 +0000 (09:11 +0200)
committerggargani <giovanni@gargani.it>
Fri, 16 Sep 2016 07:11:32 +0000 (09:11 +0200)
Reviewed regexp
Refactored in a static function in order to make it testable
Added tests

CRM/Utils/File.php
tests/phpunit/CRM/Utils/FileTest.php

index eb61db924820c722e6439ba508fdda4264f84be4..8c0a0640597fdd0dede97332e3706822728e3ad0 100644 (file)
@@ -324,7 +324,7 @@ class CRM_Utils_File {
 
     // get rid of comments starting with # and --
 
-    $string = preg_replace("/^(#|--).*\R*/m", "", $string);
+    $string = self::stripComments($string);
 
     $queries = preg_split('/;\s*$/m', $string);
     foreach ($queries as $query) {
@@ -343,6 +343,18 @@ class CRM_Utils_File {
       }
     }
   }
+  /**
+   *
+   * Strips comment from a possibly multiline SQL string
+   *
+   * @param string $string
+   *
+   * @return string
+   *  stripped string
+   */
+  public static function stripComments($string) {
+    return preg_replace("/^(#|--).*\R*/m", "", $string);
+  }
 
   /**
    * @param $ext
index 7028427da818db514c6b663e7274d31d863d58e0..db2a0a389c5bd5f2b5494167afd2369d3773cb66 100644 (file)
@@ -23,5 +23,32 @@ class CRM_Utils_FileTest extends CiviUnitTestCase {
       ));
     }
   }
+  public function testStripComment() {
+    $strings = array(
+        "\nab\n-- cd\nef"=>"\nab\nef",
+        "ab\n-- cd\nef"=>"ab\nef",
+        "ab\n-- cd\nef\ngh"=>"ab\nef\ngh",
+        "ab\n--cd\nef"=>"ab\nef",
+        "ab\n--cd\nef\n"=>"ab\nef\n",
+        "ab\n#cd\nef\n"=>"ab\nef\n",
+        "ab\n--cd\nef"=>"ab\nef",
+        "ab\n#cd\nef"=>"ab\nef",
+        "ab\nfoo#cd\nef"=>"ab\nfoo#cd\nef",
+        "ab\r\n--cd\r\nef"=>"ab\r\nef",
+        "ab\r\n#cd\r\nef"=>"ab\r\nef",
+        "ab\r\nfoo#cd\r\nef"=>"ab\r\nfoo#cd\r\nef",
+    );
+    foreach ($strings as $string => $check) {
+      $test=CRM_Utils_File::stripComments($string);
+      $this->assertEquals($test,
+          $check,
+          sprintf("original=[%s]\nstripped=[%s]\nexpected=[%s]",
+              json_encode($string),
+              json_encode($test),
+              json_encode($check)
+           )
+      );
+    }
+  }
 
 }