header text, options, * nth: field => occurrence of that header text when it is not the first (optional)}]}. */ final class TemplateStore { const OPTION = 'catalogrelay_templates'; const LIMIT = 1; /** * The saved template or null. * * @return array|null */ public static function get(): ?array { $data = get_option( self::OPTION ); if ( ! is_array( $data ) || empty( $data['templates'][0] ) || ! is_array( $data['templates'][0] ) ) { return null; } return $data['templates'][0]; } /** * Save the template (replaces the existing one: the free MVP keeps a single template). * * @param string $name Name. * @param string[] $header Header cells of the file the mapping was made for. * @param array $map Field => column index. * @param array $options Import options to remember. * @return array The stored template. */ public static function save( string $name, array $header, array $map, array $options = array() ): array { $by_field = array(); $nth = array(); foreach ( $map as $field => $index ) { if ( isset( $header[ $index ] ) && FieldRegistry::isField( (string) $field ) ) { $by_field[ (string) $field ] = trim( (string) $header[ $index ] ); // A file with two columns of the same name: remember which one (applyTemplate() resolves the same one). $k = HeaderNormalizer::key( (string) $header[ $index ] ); $n = 1; foreach ( $header as $i => $cell ) { if ( (int) $i < (int) $index && HeaderNormalizer::key( (string) $cell ) === $k ) { ++$n; } } if ( $n > 1 ) { $nth[ (string) $field ] = $n; } } } $template = array( 'name' => '' === trim( $name ) ? 'Default' : mb_substr( sanitize_text_field( $name ), 0, 80, 'UTF-8' ), 'map' => $by_field, 'options' => $options, ); if ( $nth ) { $template['nth'] = $nth; } update_option( self::OPTION, array( 'v' => 1, 'templates' => array( $template ), ), false ); return $template; } /** * Delete the template. * * @return void */ public static function delete(): void { delete_option( self::OPTION ); } }