Browse Source

added StringHelper::containsAny

Fabian Peter Hammerle 7 years ago
parent
commit
5b9f7daa2f
2 changed files with 63 additions and 0 deletions
  1. 18 0
      StringHelper.php
  2. 45 0
      tests/StringHelperTest.php

+ 18 - 0
StringHelper.php

@@ -64,4 +64,22 @@ class StringHelper
             return implode($glue, $pieces);
         }
     }
+
+    /**
+     * @throws InvalidArgumentException empty needle
+     * @param array $needles
+     * @param string $haystack
+     * @return bool
+     */
+    public static function containsAny(array $needles, $haystack)
+    {
+        foreach($needles as $needle) {
+            if(empty($needle)) {
+                throw new \InvalidArgumentException('empty needle');
+            } elseif(strpos($haystack, $needle) !== false) {
+                return true;
+            }
+        }
+        return false;
+    }
 }

+ 45 - 0
tests/StringHelperTest.php

@@ -269,4 +269,49 @@ class StringHelperTest extends \PHPUnit_Framework_TestCase
             StringHelper::implode(',', [null, null, null])
             );
     }
+
+    public function containsAnyProvider()
+    {
+        return [
+            [['a', 'b', 's'], 'string', true],
+            [['a', 'b'], 'string', false],
+            [['a'], '', false],
+            [['a'], 'string', false],
+            [['ng'], 'string', true],
+            [['ngg', 'ri'], 'string', true],
+            [['ngg'], 'string', false],
+            [['sti', 'sri'], 'string', false],
+            [['sti', 'str', 'sri'], 'string', true],
+            [['str', 'sri'], 'string', true],
+            [[], '', false],
+            [[], 'string', false],
+            ];
+    }
+
+    /**
+     * @dataProvider containsAnyProvider
+     */
+    public function testContainsAny(array $needles, $haystack, $result)
+    {
+        $this->assertSame($result, StringHelper::containsAny($needles, $haystack));
+    }
+
+    public function containsAnyEmptyNeedleProvider()
+    {
+        return [
+            [[''], ''],
+            [[''], 'string'],
+            [['a', '', 'c'], ''],
+            [['a', '', 'c'], 'string'],
+            ];
+    }
+
+    /**
+     * @dataProvider containsAnyEmptyNeedleProvider
+     * @expectedException InvalidArgumentException
+     */
+    public function testContainsAnyEmptyNeedle(array $needles, $haystack)
+    {
+        StringHelper::containsAny($needles, $haystack);
+    }
 }