Parse CSV

This method parses CSV content into a numeric array
containing an array of data for each CSV line.

@param  string $input
@return array
188764
protected function parseCsv($input)
    {
        $temp = fopen('php://memory', 'rw');
        fwrite($temp, $input);
        fseek($temp, 0);
        $res = array();
        while (($data = fgetcsv($temp)) !== false) {
            $res[] = $data;
        }
        fclose($temp);

        return $res;
    }
887262
public static function normalize(&$input)
    {
        //==============================================================================
        //      Convert ArrayObjects To Simple Array
        if ($input instanceof ArrayObject) {
            $input = $input->getArrayCopy();
            //==============================================================================
            // Normalize Contents
            self::normalize($input);

        //==============================================================================
        // Normalize Array Contents
        } elseif (is_array($input)) {
            foreach ($input as &$value) {
                self::normalize($value);
            }

            //==============================================================================
        // Normalize Bool as Strings
        } elseif (is_bool($input)) {
            $input = $input ? '1' : '0';

        //==============================================================================
        // Normalize Numbers as Strings
        } elseif (is_numeric($input)) {
            $input = strval($input);
        }

        return $input;
    }
605217
public function parse(array $input): bool
    {
        $this->resetAggregators();

        $this
            ->validateType($input)
            ->validateId($input)
            ->validateAttributes($input)
            ->validateRelationships($input);

        $hasNoErrors = $this->getJsonApiErrorCollection()->count() <= 0;

        return $hasNoErrors;
    }
316514
public function just_parse($input)
    {
        $input = $this->parse_conditions($input);
        $input = $this->parse_xml($input);
        $input = $this->postrender($input);

        return $input;
    }
131237
protected function parse ($input, $contentType)
    {
        if (isset($this->contentTypes[$contentType]) && is_callable($this->contentTypes[$contentType])) {
            $result = call_user_func($this->contentTypes[$contentType], $input);
            if ($result) {
                return $result;
            }
        }

        return $input;
    }
755018
private function cleanKeysForXml(array $input): array
    {
        $return = [];
        foreach ($input as $key => $value) {
            // first remove the line return because the regex using "." pattern prevent to include the line return in the preg_replace.
            $key = str_replace("\n", '_', $key);
            $startCharacterPattern =
                '[A-Z]|_|[a-z]|[\xC0-\xD6]|[\xD8-\xF6]|[\xF8-\x{2FF}]|[\x{370}-\x{37D}]|[\x{37F}-\x{1FFF}]|'
                . '[\x{200C}-\x{200D}]|[\x{2070}-\x{218F}]|[\x{2C00}-\x{2FEF}]|[\x{3001}-\x{D7FF}]|[\x{F900}-\x{FDCF}]'
                . '|[\x{FDF0}-\x{FFFD}]|[\x{10000}-\x{EFFFF}]';
            $characterPattern = $startCharacterPattern . '|\-|\.|[0-9]|\xB7|[\x{300}-\x{36F}]|[\x{203F}-\x{2040}]';
            $key = preg_replace('/(?!' . $characterPattern . ')./u', '_', $key);
            $key = preg_replace('/^(?!' . $startCharacterPattern . ')./u', '_', $key);
            if (is_array($value)) {
                $value = $this->cleanKeysForXml($value);
            }
            $return[$key] = $value;
        }

        return $return;
    }
1091376
public static function parseParameters( $input ) {
		if ( !isset( $input ) || !$input ) {
			return [];
		}

		$pairs = explode( '&', $input );

		$parsed = [];
		foreach ( $pairs as $pair ) {
			$split = explode( '=', $pair, 2 );
			$parameter = static::urldecode( $split[0] );
			$value = isset( $split[1] ) ? static::urldecode( $split[1] ) : '';

			if ( isset( $parsed[$parameter] ) ) {
				// We have already recieved parameter(s) with this name, so
				// add to the list of parameters with this name

				if ( is_scalar( $parsed[$parameter] ) ) {
					// This is the first duplicate, so transform scalar
					// (string) into an array so we can add the duplicates
					$parsed[$parameter] = [ $parsed[$parameter] ];
				}

				$parsed[$parameter][] = $value;
			} else {
				$parsed[$parameter] = $value;
			}
		}
		return $parsed;
	}
900825
protected function parseType(array $input)
    {
        /** @var string $type */
        /** @var string[] $types */
        extract($input);
        switch ($type) {
            case 'array':
                if (!is_array($this->{$key}))
                    return false;
                break;
            case 'int':
            case 'integer':
                if (!is_int($this->{$key}))
                    return false;
                break;
            case 'or':
                $valid = false;
                foreach ($types as $_type) {
                    if (gettype($this->{$key}) == $_type) {
                        $valid = true;
                        break;
                    }
                }
                if (!$valid) return false;
                break;
            default:
                //throw new Exception('Incorrect rule');
                return null;
        }
        return true;
    }
1086939
public function sanitize( $input ) {
		$new_input = [];
		foreach ( array_keys( (array) $input ) as $id ) {
			$new_input[ sanitize_file_name( $id ) ] = sanitize_text_field( $input[ $id ] );
		}

		return $new_input;
	}
872169
protected function doUnprocess($input)
    {
        $columns = [];
        $rows    = [];
        $cells   = [];

        $columnObjects = $input->getColumns();
        $rowObjects    = $input->getRows();

        $columnKey = 0;
        foreach ($columnObjects as $column) {
            $columns[$columnKey] = $column->getKey();
            $columnKey++;
        }

        $rowKey = 0;
        foreach ($rowObjects as $row) {
            $rows[$rowKey] = $row->getKey();

            $columnKey = 0;
            foreach ($columnObjects as $column) {
                $cells[$rowKey][$columnKey] = $row[$column];
                $columnKey++;
            }

            $rowKey++;
        }

        $data                           = [];
        $data[TableType::COLUMNS_FIELD] = $columns;

        if ($this->includeRows) {
            $data[TableType::ROWS_FIELD] = $rows;
        }

        $data[TableType::CELLS_FIELD] = $cells;


        return $data;
    }
1125145
public static function parseLines($input): array
    {
        if (is_array($input)) {
            $input = implode(PHP_EOL, $input);
        }

        return Str::parseLines($input);
    }
837562
private function load($input) {
		$Source = $this->loadFromSource($input);
		if (empty ($Source)) return array();
		$this->path = array();
		$this->result = array();


		for ($i = 0; $i < count($Source); $i++) {
			$line = $Source[$i];
			$lineIndent = $this->_getIndent($line);
			$this->path = $this->getParentPathByIndent($lineIndent);
			$line = $this->stripIndent($line, $lineIndent);
			if ($this->isComment($line)) continue;

			if ($literalBlockStyle = $this->startsLiteralBlock($line)) {
				$line = rtrim ($line, $literalBlockStyle . "\n");
				$literalBlock = '';
				$line .= $this->LiteralPlaceHolder;

				while ($this->literalBlockContinues($Source[++$i], $lineIndent)) {
					$literalBlock = $this->addLiteralLine($literalBlock, $Source[$i], $literalBlockStyle);
				}
				$i--;
			}
			$lineArray = $this->_parseLine($line);
			if ($literalBlockStyle)
			$lineArray = $this->revertLiteralPlaceHolder ($lineArray, $literalBlock);

			$this->addArray($lineArray, $lineIndent);
		}
		return $this->result;
	}
976648
public function parseManyFromArray( array $input )
    {
        $items = array();
        foreach ($input as $itemArray)
        {
            $items[] = $this->parseOneFromArray($itemArray);
        }

        return $items;
    }
461854
public static function parseMultiPartContent($input = NULL, $parseFiles = NULL)
	{
		NULL !== $input or $input = static::current()->body();
		NULL !== $parseFiles or $parseFiles = static::config('request.data.parseBodyFiles.enabled', FALSE);

		$data = [];
		$files = $parseFiles ? [] : NULL;

		// grab multipart boundary from content type header
		preg_match('/boundary=["]*([^"\s;]+)/', $_SERVER['CONTENT_TYPE'], $matches);

		if (count($matches)) {
			$boundary = preg_quote($matches[1]);

			// split content by boundary and get rid of last -- element
			$blocks = preg_split("/-+$boundary/", $input);

			// loop data blocks
			foreach ($blocks as $block) {
				if (empty($block))
					continue;

				$parts = preg_split('/[\r\n][\r\n]/', trim($block, "\r\n"), 2, PREG_SPLIT_NO_EMPTY);

				if (count($parts) != 2) continue;

				list($raw_headers, $input) = $parts;

				if (preg_match(
					'/name="([^"]+)"(; *filename="([^"]+)")?/',
					$raw_headers,
					$matches
				)) {
					$name = rawurldecode($matches[1]);
					$filename = isset($matches[3]) ? $matches[3] : NULL;

					if (!isset($filename)) {
						$input = Helpers_Text::trimAsNULL($input);
						$_tmp = "{$name}={$input}";
						$_data = NULL;
						parse_str($_tmp, $_data);
						$data = Helpers_Arr::merge($data, $_data);
					} elseif (isset($files)) {
						$_tmpname = tempnam(NULL, 'tmp');
						if (FALSE !== $_tmpname) {
							if (preg_match('@^Content-Type:@im', $input)) {
								$input = trim(preg_replace('@^Content-Type:[^\n]*@i', "", $input), "\r\n");
							}

							file_put_contents($_tmpname, $input);
							chmod($_tmpname, static::config('request.data.parseBodyFiles.chmod', 0666));

							$files[$name] = [
								'name' => $filename,
								'type' => mime_content_type($_tmpname),
								'tmp_name' => $_tmpname,
								'error' => UPLOAD_ERR_OK,
								'size' => filesize($_tmpname),
							];
						}
					}
				}
			}

			if (Kohana_Helpers_Arr::count($files)) {
				foreach ($files as $fileKey=>$fileInfo) {
					$_FILES[$fileKey] = $fileInfo;
				}

				if (static::config('request.data.parseBodyFiles.deleteOnShutdown', TRUE)) {
					register_shutdown_function(function () use ($files) {
						foreach ($files as $row) @unlink($row['tmp_name']);
					});
				}
			}
		}

		return $data;
	}
959326
public function wrap(array $input)
    {
        $out = [];
        foreach ($input as $line) {
            foreach ($this->chunk($line) as $new) {
                $out[] = $new;
            }
        }
        return $out;
    }
135266
public static function fetch($input): array
    {
        $output = [];
        $map = [];
        foreach ($input as $i => $row) {
            $model = '';
            foreach ($row as $key => $value) {
                if (strpos($key, '__') === 0) {
                    $model = substr($key, 2);
                    continue;
                }
                $map[$i][$model][$key] = $value;
            }
            foreach ($map[$i] as $model => &$data) {
                $data = self::createRow($model, $data);
            }
            $output[] = $map;
        }
        return $output;
    }
1081847
public static function parseFormData($input)
    {
        $boundary = substr($input, 0, strpos($input, "\r\n"));

        // Fetch each part
        $parts = array_slice(explode($boundary, $input), 1);
        $data = [];
        $files = [];

        foreach ($parts as $part) {
            // If this is the last part, break
            if (strpos($part, '--') === 0) {
                break;
            }

            // Separate content from headers
            $part = ltrim($part, "\r\n");

            list($rawHeaders, $content) = explode("\r\n\r\n", $part, 2);

            $content = substr($content, 0, strlen($content) - 2);

            // Parse the headers list
            $rawHeaders = explode("\r\n", $rawHeaders);
            $headers = [];

            foreach ($rawHeaders as $header) {
                list($name, $value) = explode(':', $header, 2);

                $headers[strtolower($name)] = ltrim($value, ' ');
            }

            // Parse the Content-Disposition to get the field name, etc.
            if (isset($headers['content-disposition'])) {
                $filename = null;

                preg_match(
                    '/^form-data; *name="([^"]+)"(?:; *filename="([^"]+)")?/',
                    $headers['content-disposition'],
                    $matches
                );

                $field = $matches[1];
                $fileName = (isset($matches[2]) ? $matches[2] : null);

                $fieldName = str_replace(['[', '][', ']'], ['.', '.', ''], $field);

                // If we have no filename, save the data. Otherwise, save the file.
                if ($fileName === null) {
                    static::setByPath($data, $fieldName, $content);
                } else {
                    $tempFile = tempnam(sys_get_temp_dir(), 'sfy');

                    file_put_contents($tempFile, $content);

                    $content = [
                        'name' => $fileName,
                        'type' => $headers['content-type'],
                        'tmp_name' => $tempFile,
                        'error' => 0,
                        'size' => filesize($tempFile),
                    ];

                    static::setByPath($files, $fieldName, $content);

                    register_shutdown_function(
                        function () use ($tempFile) {
                            @unlink($tempFile);
                        }
                    );
                }
            }
        }

        return [
            'data' => $data,
            'files' => $files,
        ];
    }