<?php
/*
 * Software Name: Eorisis Pixels
 * Software URI: https://eorisis.com/shop/software/joomla/pixels
 * Author: Eorisis
 * Author URI: https://eorisis.com
 * Copyright: Copyright (C) 2011-2025 EORISIS. All Rights Reserved.
 * License: GNU General Public License version 2; See https://eorisis.com/gpl
 * Terms of Service: https://eorisis.com/tos
 */
namespace com_eorisis_pixels\framework\install_package\lib\core\model;
\defined('_JEXEC') or die;

use ZipArchive;

class zip
{
	public function __construct() {}

	// --------------------------------------------------

	public function read_file_from_archive(string $target_file_path, string $archive_file_full_path)
	{
		if (!\is_file($archive_file_full_path))
		{
			return;
		}

		$zip = $this->get_zip_archive();
		if ($zip !== null && $zip->open($archive_file_full_path) === true)
		{
			$contents = $zip->getFromName($target_file_path);
			$result = $zip->close();
			return $result ? $contents : null;
		}

		// Fallback to zip extension
		$zip_string = $this->extension_string($archive_file_full_path, $target_file_path);
		if (!$zip_string)
		{
			return;
		}

		if (\com_eorisis_pixels\framework\install_package\lib\core\model\filesystem::file_extension($archive_file_full_path) == 'ini')
		{
			return (array)\parse_ini_file($zip_string);
		}

		return (string)\file_get_contents($zip_string);
	}

	// --------------------------------------------------

	private function get_zip_archive()
	{
		if (\class_exists('ZipArchive', false))
		{
			return new ZipArchive;
		}
	}

	// --------------------------------------------------

	private function extension_string(string $archive_file_full_path, string $target_file_path)
	{
		if (!\extension_loaded('zip'))
		{
			return;
		}

		return 'zip://'.$archive_file_full_path.'#'.$target_file_path;
	}
}
