@@ -605,4 +605,81 @@ class ObjectSerializer
605605
606606 return $qs ? (string) substr($qs, 0, -1) : '';
607607 }
608+
609+ /**
610+ * Flattens an array of Model object and generates an array compatible
611+ * with formdata - a single-level array where the keys use bracket
612+ * notation to signify nested data.
613+ *
614+ * @param \ArrayAccess|array $source
615+ *
616+ * credit: https://github.com/FranBar1966/FlatPHP
617+ */
618+ private static function flatten_array(
619+ mixed $source,
620+ array & $destination,
621+ string $start = '',
622+ ) {
623+ $opt = [
624+ ' prefix' => ' [' ,
625+ ' suffix' => ' ]' ,
626+ ' suffix-end' => true ,
627+ ' prefix-list' => ' [' ,
628+ ' suffix-list' => ' ]' ,
629+ ' suffix-list-end' => true ,
630+ ];
631+
632+ if (! is_array($source )) {
633+ $source = (array) $source ;
634+ }
635+
636+ /**
637+ * array_is_list only in PHP >= 8.1
638+ *
639+ * credit: https://www.php.net/manual/en/function.array-is-list.php#127044
640+ */
641+ if (!function_exists('array_is_list')) {
642+ function array_is_list(array $array )
643+ {
644+ $i = -1;
645+
646+ foreach ($array as $k => $v ) {
647+ ++$i ;
648+ if ($k !== $i ) {
649+ return false ;
650+ }
651+ }
652+
653+ return true;
654+ }
655+ }
656+
657+ if (array_is_list($source)) {
658+ $currentPrefix = $opt [' prefix-list' ];
659+ $currentSuffix = $opt [' suffix-list' ];
660+ $currentSuffixEnd = $opt [' suffix-list-end' ];
661+ } else {
662+ $currentPrefix = $opt [' prefix' ];
663+ $currentSuffix = $opt [' suffix' ];
664+ $currentSuffixEnd = $opt [' suffix-end' ];
665+ }
666+
667+ $currentName = $start;
668+
669+ foreach ($source as $key => $val) {
670+ $currentName .= $currentPrefix .$key ;
671+
672+ if (is_array($val ) && ! empty($val )) {
673+ $currentName .= " {$currentSuffix}" ;
674+ self::flatten_array($val , $destination , $currentName );
675+ } else {
676+ if ($currentSuffixEnd ) {
677+ $currentName .= $currentSuffix ;
678+ }
679+ $destination[$currentName] = self::toString($val);
680+ }
681+
682+ $currentName = $start;
683+ }
684+ }
608685}
0 commit comments