Allow Polymorphic_Field_Helper::parse() to accept array and object inputs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
root
2026-01-07 06:09:04 +00:00
parent 36979e4b52
commit ff04f85403

View File

@@ -5,11 +5,15 @@ namespace App\RSpade\Core;
/**
* Polymorphic Field Helper
*
* Handles JSON-encoded polymorphic field values from form components.
* Handles polymorphic field values from form components.
* Provides parsing, validation, and security checks for polymorphic relationships.
*
* Polymorphic fields are submitted as JSON: {"model":"Contact_Model","id":123}
* This class parses that JSON and validates the model type against a whitelist.
* Accepts multiple input formats:
* - JSON string: '{"model":"Contact_Model","id":123}'
* - Array: ['model' => 'Contact_Model', 'id' => 123]
* - Object: stdClass with model and id properties
*
* Validates the model type against a whitelist of allowed classes.
*
* Usage in controllers:
*
@@ -67,23 +71,40 @@ class Polymorphic_Field_Helper
private array $allowed_models = [];
/**
* Parse a JSON-encoded polymorphic field value
* Parse a polymorphic field value
*
* @param string|null $json_value The JSON string from form submission (e.g., '{"model":"Contact_Model","id":123}')
* Accepts multiple formats:
* - JSON string: '{"model":"Contact_Model","id":123}'
* - Array: ['model' => 'Contact_Model', 'id' => 123]
* - Object: stdClass with model and id properties
*
* @param string|array|object|null $value The polymorphic value in any supported format
* @param array $allowed_model_classes Array of allowed model class names (use Model::class syntax)
* @return self
*/
public static function parse(?string $json_value, array $allowed_model_classes): self
public static function parse(string|array|object|null $value, array $allowed_model_classes): self
{
$instance = new self();
$instance->allowed_models = array_map(fn($class) => class_basename($class), $allowed_model_classes);
if (empty($json_value)) {
if (empty($value)) {
return $instance;
}
$decoded = json_decode($json_value, true);
if (!is_array($decoded)) {
// Normalize to array
$decoded = null;
if (is_string($value)) {
$decoded = json_decode($value, true);
if (!is_array($decoded)) {
return $instance;
}
} elseif (is_object($value)) {
$decoded = (array) $value;
} elseif (is_array($value)) {
$decoded = $value;
}
if (!$decoded) {
return $instance;
}