/** * @throws \Rs\Json\Patch\FailedTestException * @return string */ public function apply() { $patchOperations = $this->jsonPatchDocument->getPatchOperations(); $patchedDocument = $this->targetDocument; $wasObject = '{' === mb_substr(trim($patchedDocument), 0, 1); foreach ($patchOperations as $index => $patchOperation) { $targetDocument = $patchOperation->perform($patchedDocument); if ($patchOperation instanceof Test && $targetDocument === false) { $exceptionMessage = 'Failed on Test PatchOperation at index: ' . $index; throw new FailedTestException($exceptionMessage); } if (!$patchOperation instanceof Test) { $patchedDocument = $targetDocument; } } $emptyArray = '[]'; $emptyObject = '{}'; if ($patchedDocument === $emptyArray && $wasObject) { $patchedDocument = $emptyObject; } if ($patchedDocument === $emptyObject && !$wasObject) { $patchedDocument = $emptyArray; } return $patchedDocument; }