/** * Quote all values of an array according to their type * * @param array $array * @return array */ public function quote(array $array) { foreach ($array as &$value) { $value = is_array($value) ? self::quote($value) : StringUtils::quote($value); } return $array; }
/** * Encode an array into INI format * * <code> * // Default $options * $options = [ * 'default_section' => 'settings', * 'allow_fake_first' => true * ] * </code> * * @param mixed $resource * @param array $options */ public function fromArray(array $resource, array $options = []) { $options = array_merge(['default_section' => 'settings', 'allow_fake_first' => true], $options); $quoteArgs = ['enclosure' => '"', 'escape' => '\\']; // fake a section in case the array is not deep enough if (count($resource) && $options['allow_fake_first'] && !is_array(current($resource))) { $resource = [$options['default_section'] => $resource]; } $ini = ''; foreach ($resource as $l1Key => $l1Val) { if (is_array($l1Val)) { $ini .= "\n" . '[' . $l1Key . ']' . "\n"; foreach ($l1Val as $l2Key => $l2Val) { if (is_array($l2Val)) { foreach ($l2Val as $l3Key => $l3Val) { if (is_array($l3Val)) { throw new JigException('$resource must not have more than three levels'); } $ini .= $l2Key . '[' . $l3Key . '] = ' . StringUtils::quote($l3Val, $quoteArgs) . "\n"; } } else { $ini .= $l2Key . ' = ' . StringUtils::quote($l2Val, $quoteArgs) . "\n"; } } } else { $ini .= $l1Key . ' = ' . StringUtils::quote($l1Val, $quoteArgs) . "\n"; } } return trim($ini); }
/** * {@inheritdoc} * * Source format: CSV * * <code> * $options = [ * 'delimiter' => ',', // typically ,|;|\t * 'enclosure' => '"', // typically "|' * 'escape' => '\\', // how the above is to be escaped * 'pivot' => false // pivot input array * ]; * </code> * * @param mixed $resource * @param array $options */ public function fromArray($resource, array $options = []) { $options = array_merge(['delimiter' => ',', 'enclosure' => '"', 'escape' => '\\', 'pivot' => false], $options); $resource = parent::getRealResource($resource, $options); if ($options['pivot']) { $resource = ArrayUtils::pivot($resource); } $dataDepth = self::verifyDataDepthLimit($resource, 2); if ($dataDepth === 1) { $resource = [$resource]; } else { if ($dataDepth > 2) { $msg = '$resource must have one or two levels'; if ($options['pivot']) { $msg .= ' after it has been pivoted'; } throw new JigException($msg); } } $csv = ''; foreach ($resource as $valueArr) { $line = ''; foreach ($valueArr as $value) { $line .= StringUtils::quote($value, $options) . $options['delimiter']; } $csv .= rtrim($line, $options['delimiter']) . PHP_EOL; } return $csv; }