<?php
/**
 * Sitemap Sanitizer
 *
 * Sanitizes filenames, prefixes, and slugs used by the sitemap cache.
 *
 * @package SEOvaultSEO
 */

namespace SEOvaultSEO\Sitemap;

/**
 * Sanitization helpers for sitemap files and slugs
 */
class Sanitizer {

	/**
	 * Sanitize a filename. Rejects directory traversal and normalizes separators.
	 *
	 * @param string $filename Filename or relative path.
	 * @return string
	 */
	public static function filename( $filename ) {
		if ( ! is_string( $filename ) || '' === $filename ) {
			return '';
		}

		$filename = str_replace( '\\', '/', $filename );
		if ( false !== strpos( $filename, '..' ) ) {
			return '';
		}

		$filename = ltrim( $filename, '/' );

		$parts = explode( '/', $filename );
		$clean = array();
		foreach ( $parts as $part ) {
			if ( '' === $part || '.' === $part || '..' === $part ) {
				continue;
			}
			$clean[] = sanitize_file_name( $part );
		}

		if ( empty( $clean ) ) {
			return '';
		}

		return implode( '/', $clean );
	}

	/**
	 * Sanitize a prefix. Only allows [A-Za-z0-9_-].
	 *
	 * @param string $prefix Prefix.
	 * @return string
	 */
	public static function prefix( $prefix ) {
		if ( ! is_string( $prefix ) ) {
			return '';
		}
		return preg_replace( '/[^A-Za-z0-9_-]/', '', $prefix );
	}

	/**
	 * Sanitize a slug. Only allows lowercase letters, numbers, dash, underscore.
	 *
	 * @param string $slug Slug.
	 * @return string
	 */
	public static function slug( $slug ) {
		if ( ! is_string( $slug ) ) {
			return '';
		}
		$slug = preg_replace( '/[^a-z0-9_-]/', '', strtolower( $slug ) );
		return (string) $slug;
	}
}
