<?php
/**
 * Writes a PHP array of metadata to a file.
 *
 * @package SolidWP\Performance
 */

declare( strict_types=1 );

namespace SolidWP\Performance\Page_Cache\Meta\Writers;

use RuntimeException;
use SolidWP\Performance\Page_Cache\Meta\Contracts\Meta_Writer;
use SolidWP\Performance\Page_Cache\Meta\Exceptions\MetadataNotWritableException;
use SolidWP\Performance\Page_Cache\Meta\Meta;
use SolidWP\Performance\Page_Cache\Meta\Meta_File;

/**
 * Writes a PHP array of metadata to a file.
 *
 * @package SolidWP\Performance
 */
final class Array_File_Writer implements Meta_Writer {

	/**
	 * @var Meta_File
	 */
	private Meta_File $meta_file;

	/**
	 * @param Meta_File $meta_file The meta file.
	 */
	public function __construct( Meta_File $meta_file ) {
		$this->meta_file = $meta_file;
	}

	/**
	 * Write metadata to a meta file.
	 *
	 * @param Meta $meta The Meta value object.
	 *
	 * @throws MetadataNotWritableException If we can't save the metadata.
	 *
	 * @return void
	 */
	public function write( Meta $meta ): void {
		$content = "<?php\n // this file is automatically generated. Do not edit.\nreturn " . var_export( $meta->to_array(), true ) . ";\n";
		$path    = $this->meta_file->get_path_from_url( $meta->url );
		$dir     = dirname( $path );

		if ( ! is_dir( $dir ) ) {
			$result = wp_mkdir_p( $dir );

			if ( ! $result ) {
				throw new MetadataNotWritableException( "Unable to create metadata directory: $dir" );
			}
		}

		if ( false === file_put_contents( $path, $content, LOCK_EX ) ) {
			throw new MetadataNotWritableException( "Unable to write metadata to: $path" );

		}
	}

	/**
	 * Deletes a meta file.
	 *
	 * @param Meta $meta The Meta value object.
	 *
	 * @throws RuntimeException If the URL is malformed.
	 *
	 * @return void
	 */
	public function delete( Meta $meta ): void {
		$path = $this->meta_file->get_path_from_url( $meta->url );

		if ( ! is_writable( $path ) ) {
			return;
		}

		unlink( $path );
	}
}
