array(), 'products' => array(), 'categories' => array(), ); $current_section = null; $section_lines = array(); foreach ( $lines as $line ) { if ( trim( $line ) === '' ) { continue; } if ( $line !== '' && $line[0] !== ' ' && $line[0] !== "\t" ) { if ( $current_section !== null && ! empty( $section_lines ) ) { $result[ $current_section ] = $this->parseSection( $current_section, $section_lines ); } if ( strpos( $line, 'meta:' ) === 0 ) { $current_section = 'meta'; $section_lines = array(); } elseif ( strpos( $line, 'products' ) === 0 ) { $current_section = 'products'; $section_lines = array( $line ); } elseif ( strpos( $line, 'categories:' ) === 0 ) { $current_section = 'categories'; $section_lines = array(); } continue; } if ( $current_section !== null ) { $section_lines[] = $line; } } if ( $current_section !== null && ! empty( $section_lines ) ) { $result[ $current_section ] = $this->parseSection( $current_section, $section_lines ); } return $result; } /** * The products of a TOON index one at a time, in file order. * * Reads the products section as decode() does (trailing whitespace * trimmed, blank lines skipped, the section ending at the next unindented * line), without the products array decode() builds or a copy of the text * split into lines: a caller that needs one product at a time holds only * the text and that product. Products are not keyed by id, so a repeated * id is yielded each time it appears. * * @param string $toon TOON-formatted string. * @return \Generator> Each product as decode() returns it. * @throws \RuntimeException When the products header is malformed, on the first step. */ public function products( string $toon ): \Generator { $offset = $this->sectionOffset( $toon, 'products' ); if ( null === $offset ) { return; } list( $header, $offset ) = $this->lineAt( $toon, $offset ); $fields = $this->productFields( rtrim( $header ) ); if ( empty( $fields ) ) { return; } $length = strlen( $toon ); while ( $offset < $length ) { list( $line, $offset ) = $this->lineAt( $toon, $offset ); $line = rtrim( $line ); if ( trim( $line ) === '' ) { continue; } if ( $line[0] !== ' ' && $line[0] !== "\t" ) { return; } yield $this->productRow( ltrim( $line ), $fields ); } } /** * The categories section of a TOON index alone, as decode() returns it. * * @param string $toon TOON-formatted string. * @return array Categories keyed by ID. */ public function categories( string $toon ): array { $offset = $this->sectionOffset( $toon, 'categories:' ); if ( null === $offset ) { return array(); } list( , $offset ) = $this->lineAt( $toon, $offset ); $lines = array(); $length = strlen( $toon ); while ( $offset < $length ) { list( $line, $offset ) = $this->lineAt( $toon, $offset ); $line = rtrim( $line ); if ( trim( $line ) === '' ) { continue; } if ( $line[0] !== ' ' && $line[0] !== "\t" ) { break; } $lines[] = $line; } return $this->parseKeyedCategories( $lines ); } /** * Where the first unindented line that starts with $header begins. * * A value never holds a raw newline (the encoder escapes it), so a * newline followed by the header can only start that line. * * @param string $toon TOON-formatted string. * @param string $header Start of the section header line. * @return int|null Offset of the header line, or null when there is none. */ private function sectionOffset( string $toon, string $header ): ?int { if ( 0 === strpos( $toon, $header ) ) { return 0; } $found = strpos( $toon, "\n" . $header ); return false === $found ? null : $found + 1; } /** * The line that starts at $offset, without its newline, and the offset * of the line after it. * * @param string $toon TOON-formatted string. * @param int $offset Start of the line. * @return array{0:string,1:int} */ private function lineAt( string $toon, int $offset ): array { $end = strpos( $toon, "\n", $offset ); if ( false === $end ) { return array( substr( $toon, $offset ), strlen( $toon ) ); } return array( substr( $toon, $offset, $end - $offset ), $end + 1 ); } /** * Validate TOON structure without full decode. * * Performs lightweight regex-based validation to check for required * section headers. This is much faster than a full decode. * * @param string $toon TOON-formatted string. * @return bool True if valid structure. */ public function validate( string $toon ): bool { $has_meta = preg_match( '/^meta:/m', $toon ); $has_products = preg_match( '/^products\[\d+\]\{[^}]*\}:/m', $toon ); $has_categories = preg_match( '/^categories:/m', $toon ); if ( ! $has_meta || ! $has_products || ! $has_categories ) { return false; } $has_meta_content = preg_match( '/^meta:\s*\n\s+[\w-]+:/m', $toon ); return (bool) $has_meta_content; } /** * Parse a section based on its type. * * @param string $section Section name. * @param string[] $lines Section lines. * @return array Parsed section data. */ private function parseSection( string $section, array $lines ): array { switch ( $section ) { case 'meta': return $this->parseNestedObject( $lines, 1 ); case 'products': return $this->parseTabularProducts( $lines ); case 'categories': return $this->parseKeyedCategories( $lines ); default: return array(); } } /** * Parse nested object from indented lines. * * @param string[] $lines Lines to parse. * @param int $indent_level Expected indentation level. * @return array Parsed object. */ private function parseNestedObject( array $lines, int $indent_level ): array { $result = array(); $current_key = null; $nested_lines = array(); $indent_str = str_repeat( ' ', $indent_level ); $next_indent = str_repeat( ' ', $indent_level + 1 ); foreach ( $lines as $line ) { if ( strpos( $line, $indent_str ) === 0 && ( ! isset( $line[ strlen( $indent_str ) ] ) || $line[ strlen( $indent_str ) ] !== ' ' ) ) { if ( $current_key !== null && ! empty( $nested_lines ) ) { $result[ $current_key ] = $this->parseNestedObject( $nested_lines, $indent_level + 1 ); $nested_lines = array(); } $content = substr( $line, strlen( $indent_str ) ); if ( preg_match( '/^([\w-]+):$/', $content, $matches ) ) { $current_key = $matches[1]; continue; } $parsed = $this->parseKeyValue( $content ); if ( $parsed !== null ) { $result[ $parsed['key'] ] = $parsed['value']; $current_key = null; } } elseif ( $current_key !== null && strpos( $line, $next_indent ) === 0 ) { $nested_lines[] = $line; } } if ( $current_key !== null && ! empty( $nested_lines ) ) { $result[ $current_key ] = $this->parseNestedObject( $nested_lines, $indent_level + 1 ); } return $result; } /** * Parse tabular products section. * * @param string[] $lines Section lines including header. * @return array Products keyed by ID. */ private function parseTabularProducts( array $lines ): array { if ( empty( $lines ) ) { return array(); } $fields = $this->productFields( $lines[0] ); if ( empty( $fields ) ) { return array(); } $products = array(); for ( $i = 1; $i < count( $lines ); $i++ ) { $row_line = ltrim( $lines[ $i ] ); if ( $row_line === '' ) { continue; } $product = $this->productRow( $row_line, $fields ); $product_id = (string) $product['id']; $products[ $product_id ] = $product; } return $products; } /** * The field names of a products header: products[N]{field1,field2,...}: * * @param string $header Products header line. * @return string[] Field names, none for a table without rows. * @throws \RuntimeException When the header is malformed. */ private function productFields( string $header ): array { if ( ! preg_match( '/^products\[(\d+)\]\{([^}]+)\}:/', $header, $matches ) ) { if ( preg_match( '/^products\[0\]/', $header ) ) { return array(); } // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped throw new \RuntimeException( 'Invalid products header: ' . $header ); } if ( (int) $matches[1] === 0 ) { return array(); } return explode( ',', $matches[2] ); } /** * One product from a row of the products table. * * @param string $row_line Row without its indentation. * @param string[] $fields Field names from the header. * @return array The product, a missing cell read as null. */ private function productRow( string $row_line, array $fields ): array { $values = $this->parseTabularRow( $row_line, count( $fields ) ); $product = array(); foreach ( $fields as $idx => $field ) { $product[ $field ] = $values[ $idx ] ?? null; } return $product; } /** * Parse a tabular row into values. * * @param string $row Row string. * @param int $num_fields Expected number of fields (unused, kept for interface). * @return array Parsed values. */ private function parseTabularRow( string $row, int $num_fields ): array { return $this->parseCommaSeparated( $row ); } /** * Parse comma-separated values with quote and escape handling. * * This is the core parsing logic used by both parseTabularRow and parseSimpleArray. * * @param string $str Input string. * @return array Parsed scalar values. */ private function parseCommaSeparated( string $str ): array { $values = array(); $current = ''; $in_quote = false; $quoted = false; $literal = false; $len = strlen( $str ); $i = 0; while ( $i < $len ) { $run = strcspn( $str, $in_quote ? '"\\' : '",', $i ); if ( $run > 0 ) { $current .= substr( $str, $i, $run ); $i += $run; if ( $i >= $len ) { break; } } $char = $str[ $i ]; ++$i; if ( $char === '\\' ) { if ( $i >= $len ) { break; } $escaped = $str[ $i ]; ++$i; switch ( $escaped ) { case 'n': $current .= "\n"; break; case 'r': $current .= "\r"; break; case 't': $current .= "\t"; break; case '"': $current .= '"'; break; case '\\': $current .= '\\'; break; default: if ( $current === '' && ( $escaped === '[' || $escaped === '{' ) ) { $literal = true; } $current .= $escaped; } continue; } if ( $char === '"' ) { $in_quote = ! $in_quote; $quoted = true; continue; } $values[] = $this->parseCell( $current, $quoted, $literal ); $current = ''; $quoted = false; $literal = false; } if ( $current !== '' || $quoted || ! empty( $values ) ) { $values[] = $this->parseCell( $current, $quoted, $literal ); } return $values; } /** * Parse one comma-separated cell whose quotes were already stripped. * * A quoted cell is a string unless it holds a JSON container and did not * start with the \[ or \{ escape; an unquoted cell is typed by parseScalarValue(), which also keeps files written before * the encoder quoted scalar lookalikes readable. * * @param string $cell Unescaped cell text. * @param bool $quoted Whether the cell was quoted in the source. * @param bool $literal Whether the cell began with a \[ or \{ escape. * @return mixed Parsed value. */ private function parseCell( string $cell, bool $quoted, bool $literal = false ) { if ( ! $quoted ) { return $this->parseScalarValue( $cell ); } if ( $literal ) { return $cell; } $container = $this->decodeJsonContainer( $cell ); return $container ?? $cell; } /** * Decode text shaped like a JSON array or object. * * @param string $text Candidate text. * @return array|null Decoded container, or null when the text is not one. */ private function decodeJsonContainer( string $text ): ?array { $first = $text !== '' ? $text[0] : ''; $last = $text !== '' ? $text[ strlen( $text ) - 1 ] : ''; if ( ! ( ( $first === '[' && $last === ']' ) || ( $first === '{' && $last === '}' ) ) ) { return null; } $decoded = json_decode( $text, true ); if ( json_last_error() !== JSON_ERROR_NONE || ! is_array( $decoded ) ) { return null; } return $first === '[' ? $this->castDecodedArray( $decoded ) : $decoded; } /** * Parse keyed categories section. * * @param string[] $lines Section lines. * @return array Categories keyed by ID. */ private function parseKeyedCategories( array $lines ): array { $categories = array(); $current_cat_id = null; $cat_lines = array(); foreach ( $lines as $line ) { if ( preg_match( '/^ (\d+):$/', $line, $matches ) ) { if ( $current_cat_id !== null && ! empty( $cat_lines ) ) { $categories[ $current_cat_id ] = $this->parseCategoryObject( $cat_lines ); } $current_cat_id = $matches[1]; $cat_lines = array(); continue; } if ( $current_cat_id !== null ) { $cat_lines[] = $line; } } if ( $current_cat_id !== null && ! empty( $cat_lines ) ) { $categories[ $current_cat_id ] = $this->parseCategoryObject( $cat_lines ); } return $categories; } /** * Parse a category object from its lines. * * @param string[] $lines Category lines. * @return array Category data. */ private function parseCategoryObject( array $lines ): array { $result = array(); foreach ( $lines as $line ) { $content = substr( $line, 4 ); $parsed = $this->parseKeyValue( $content ); if ( $parsed !== null ) { $result[ $parsed['key'] ] = $parsed['value']; } } return $result; } /** * Parse a key-value line. * * Handles: * - Simple: key: value * - Array: key[N]: v1,v2,v3 * - Empty array: key[0]: * * Keys can contain alphanumeric characters, underscores, and dashes. * This supports WooCommerce attribute keys like "pa_my-attr" and custom fields. * * @param string $content Line content. * @return array|null Parsed key/value or null. */ private function parseKeyValue( string $content ): ?array { if ( preg_match( '/^([\w-]+)\[(\d+)\]:\s*(.*)$/', $content, $matches ) ) { $key = $matches[1]; $count = (int) $matches[2]; $rest = $matches[3]; if ( $count === 0 || $rest === '' ) { return array( 'key' => $key, 'value' => array(), ); } $values = $this->parseSimpleArray( $rest ); return array( 'key' => $key, 'value' => $values, ); } if ( preg_match( '/^([\w-]+):\s*(.*)$/', $content, $matches ) ) { $key = $matches[1]; $value = $this->parseScalarValue( $matches[2] ); return array( 'key' => $key, 'value' => $value, ); } return null; } /** * Parse a simple comma-separated array. * * @param string $str Array string. * @return array Parsed values. */ private function parseSimpleArray( string $str ): array { return $this->parseCommaSeparated( $str ); } /** * Parse a scalar value from string. * * @param string $str Value string. * @return mixed Parsed value (int, float, bool, null, string, or array). */ private function parseScalarValue( string $str ) { $str = trim( $str ); if ( $str === 'null' ) { return null; } if ( $str === 'true' ) { return true; } if ( $str === 'false' ) { return false; } if ( preg_match( '/^-?\d+$/', $str ) ) { return (int) $str; } if ( preg_match( '/^-?\d+\.\d+$/', $str ) || preg_match( '/^-?\d+[eE][+-]?\d+$/', $str ) ) { return (float) $str; } if ( strpos( $str, '[' ) === 0 && strrpos( $str, ']' ) === strlen( $str ) - 1 ) { $decoded = json_decode( $str, true ); if ( json_last_error() === JSON_ERROR_NONE && is_array( $decoded ) ) { return $this->castDecodedArray( $decoded ); } } if ( strlen( $str ) >= 2 && $str[0] === '"' && $str[ strlen( $str ) - 1 ] === '"' ) { $unquoted = substr( $str, 1, -1 ); $literal = isset( $unquoted[1] ) && '\\' === $unquoted[0] && ( '[' === $unquoted[1] || '{' === $unquoted[1] ); if ( $literal ) { $unquoted = substr( $unquoted, 1 ); } $unquoted = preg_replace_callback( '/\\\\(n|r|t|"|\\\\)/', function ( $matches ) { switch ( $matches[1] ) { case 'n': return "\n"; case 'r': return "\r"; case 't': return "\t"; case '"': return '"'; case '\\': return '\\'; default: return $matches[0]; } }, $unquoted ); if ( ! $literal && strpos( $unquoted, '[' ) === 0 && strrpos( $unquoted, ']' ) === strlen( $unquoted ) - 1 ) { $decoded = json_decode( $unquoted, true ); if ( json_last_error() === JSON_ERROR_NONE && is_array( $decoded ) ) { return $this->castDecodedArray( $decoded ); } } return $unquoted; } return $str; } /** * A JSON-decoded array field's elements, int-cast only when every one of * them is genuinely numeric (a category/tag ID array) and left as * decoded otherwise (a string array, e.g. a grouped product's child * names) -- the encoder quotes both shapes identically, so this is the * only point left where they can be told apart. * * @param array $decoded Already json_decode()d array. * @return array Int array when every element is numeric, the array * unchanged otherwise. */ private function castDecodedArray( array $decoded ): array { $is_numeric = array_reduce( $decoded, function ( $carry, $item ) { return $carry && is_numeric( $item ); }, true ); return $is_numeric ? array_map( 'intval', $decoded ) : $decoded; } }