<?php
/**
 * Please see weepie-framework.php for more details.
 */

namespace WpieFw\Exceptions;

use WpieFw\Framework\Logger\WpieErrorLogger;

if( ! defined( 'ABSPATH' ) ) exit;

/**
 * Please see weepie-framework.php for more details.
 */

/**
 * WpieExceptionLogger class
 *
 * @author $Author: Vincent Weber <weepie-plugins@outlook.com> $
 *
 * @since 2.0
 */
final class WpieExceptionLogger extends WpieErrorLogger
{
	/**
	 * Log an Exception message
	 *
	 * @param \Throwable|\Exception $exception
	 * @param bool $whenLoggedIn indicates that message only should be logged when user is logged in
	 *
	 * @uses parent::logMessage()
	 *
	 * @since 2.0
	 */
	public static function log( $exception, $whenLoggedIn = false )
	{
		if( self::isValid( $exception ) && '' !== $exception->getMessage() ) {
			parent::logMessage( $exception->getMessage().' in '.$exception->getFile().':'.$exception->getLine(), $whenLoggedIn );
		}
	}

	/**
	 * Determine if given exception object is valid
	 *
	 * For PHP >= 7 a Throwable interface is expected
	 * For PHP < 7 an Exception interface is expected
	 *
	 * @param \Throwable|\Exception $exception
	 * @return boolean
	 */
	private static function isValid( $exception )
	{
		$phpVersion7 = version_compare( phpversion(), '7.0', '>=');

		if( $phpVersion7 && !is_a( $exception, 'Throwable' ) ) {
			return false;
		} elseif( !$phpVersion7 && !is_a( $exception, 'Exception' ) ) {
			return false;
		} else {
			return true;
		}
	}
}