Fix dev/core#4483
authorcolemanw <coleman@civicrm.org>
Thu, 10 Aug 2023 00:51:32 +0000 (20:51 -0400)
committercolemanw <coleman@civicrm.org>
Thu, 10 Aug 2023 00:51:32 +0000 (20:51 -0400)
Civi/Api4/Utils/FormattingUtil.php
tests/phpunit/api/v4/Utils/FormattingUtilTest.php [new file with mode: 0644]

index 9498079c3fce8960ddb5ea291369afca675cfd5a..ca0a681260d4de90a0b429668414618e2cdfa336 100644 (file)
@@ -446,7 +446,7 @@ class FormattingUtil {
    * @return array
    */
   public static function filterByPath(array $values, string $fieldPath, string $fieldName): array {
-    $prefix = substr($fieldPath, 0, strpos($fieldPath, $fieldName));
+    $prefix = substr($fieldPath, 0, strrpos($fieldPath, $fieldName));
     return \CRM_Utils_Array::filterByPrefix($values, $prefix);
   }
 
diff --git a/tests/phpunit/api/v4/Utils/FormattingUtilTest.php b/tests/phpunit/api/v4/Utils/FormattingUtilTest.php
new file mode 100644 (file)
index 0000000..1f19ef4
--- /dev/null
@@ -0,0 +1,42 @@
+<?php
+
+namespace api\v4\Utils;
+
+use api\v4\Api4TestBase;
+use Civi\Api4\Utils\FormattingUtil;
+
+/**
+ * @group headless
+ */
+class FormattingUtilTest extends Api4TestBase {
+
+  /**
+   * @dataProvider getFilterByPathExamples
+   * @param string $fieldPath
+   * @param string $fieldName
+   * @param array $originalValues
+   * @param array $expectedValues
+   */
+  public function testFilterByPath(string $fieldPath, string $fieldName, array $originalValues, array $expectedValues): void {
+    $this->assertEquals($expectedValues, FormattingUtil::filterByPath($originalValues, $fieldPath, $fieldName));
+  }
+
+  public function getFilterByPathExamples(): array {
+    $originalValueSets = [
+      [
+        'id' => 'a',
+        'name' => 'a_name',
+        'id_foo.id' => 'b',
+        'id_foo.name' => 'b_name',
+        'id.id_foo.id' => 'c',
+        'id.id_foo.name' => 'c_name',
+      ],
+    ];
+    return [
+      ['id', 'id', $originalValueSets[0], $originalValueSets[0]],
+      ['id_foo.id', 'id', $originalValueSets[0], ['id' => 'b', 'name' => 'b_name']],
+      ['id.id_foo.id', 'id', $originalValueSets[0], ['id' => 'c', 'name' => 'c_name']],
+    ];
+  }
+
+}