<?php
/**
 * The file contains definition of Autoloader class
 *
 * @category Class file
 * @package WLC\Algolia
 * @author White Label Coders
 * @license TO DO
 * @link TO DO
 */

namespace wlc_algolia;

defined( 'ABSPATH' ) || die( 'Direct file access is forbidden' );

/**
 * Autoloader class
 */
class Autoloader {
	/**
	 * Path to the includes directory.
	 *
	 * @var string
	 */
	private $include_path = '';

	/**
	 * The Constructor.
	 */
	public function __construct() {
		spl_autoload_register( array( $this, 'autoload' ) );

		$this->include_path = untrailingslashit( plugin_dir_path( WLC_ALGOLIA_PLUGIN_FILE ) ) . '/includes/classes/';
	}

	/**
	 * Auto-load classes on demand to reduce memory consumption.
	 *
	 * @param string $requested_class Class name.
	 */
	public function autoload( $requested_class ) {
		$requested_class = strtolower( $requested_class );

		$file = $this->get_file_name_from_class( $requested_class );

		$this->load_file( $this->include_path . $file );
	}

	/**
	 * Take a class name and turn it into a file name.
	 *
	 * @param  string $requested_class Class name.
	 * @return string
	 */
	private function get_file_name_from_class( $requested_class ) {
		$parts = explode( '\\', $requested_class );

		$class_name = end( $parts );
		$class_name = strtolower( $class_name );
		$class_name = str_replace( '_', '-', $class_name );

		return 'class-' . $class_name . '.php';
	}

	/**
	 * Include a class file.
	 *
	 * @param  string $path File path.
	 * @return bool Successful or not.
	 */
	private function load_file( $path ) {
		if ( $path && is_readable( $path ) ) {
			include_once $path;
			return true;
		}
		return false;
	}
}

new Autoloader();
