<?php

namespace T4\Helper;

use Joomla\CMS\Filesystem\File;

class Joomla
{
	// Create alias class for original call in $filepath, then overload the class
	public static function makeAlias($filepath, $originClassName, $aliasClassName)
	{
		if (!is_file($filepath)) return false;
		$cachePath = JPATH_CACHE . '/t4core/';
		$fileInfo = pathinfo($filepath);
		$target = $cachePath . $fileInfo['basename'];

		$coreVersionFile = $cachePath . '/coreVersion-' . md5($filepath) . '.txt';
		if (!is_file($coreVersionFile)) {
			File::write($coreVersionFile, '');
		}

		$coreVersion = file_get_contents($coreVersionFile);
		$currentCoreVersion = md5(JVERSION . '-' . T4VERSION);

		if (!is_file($target) || $coreVersion !== $currentCoreVersion) {
			$code = file_get_contents($filepath);
			$code = str_replace('class ' . $originClassName, 'class ' . $aliasClassName, $code);

			File::write($target, $code);
			File::write($coreVersionFile, $currentCoreVersion);
		}

		require_once $target;

		return true;
	}
}
