<?php
/**
 * A class for purifying HTML.
 */

declare(strict_types=1);
namespace FeData\FastEvents\Utilities;

use HTMLPurifier;
use HTMLPurifier_AttrDef_CSS_Percentage;
use HTMLPurifier_AttrDef_Enum;
use HTMLPurifier_Config;
use HTMLPurifier_Exception;
use stdClass;

/**
 * A class for purifying HTML.
 */
class CheckHtml {
	/**
	 * HTML Purifier for HTML content
	 *
	 * @since 1.0
	 *
	 * @return HTMLPurifier
	 */
	public static function purify(): HTMLPurifier {
		// Boot the HTML Purifier.
		$config = HTMLPurifier_Config::createDefault();
		$config->set( 'HTML.Trusted', true );
		$config->set( 'Attr.EnableID', true );

		// No cache.
		$config->set( 'Cache.DefinitionImpl', null );

		// Set some CSS flags.
		$config->set( 'CSS.AllowImportant', true );
		$config->set( 'CSS.AllowTricky', true );
		$config->set( 'CSS.Proprietary', true );
		$config->set( 'CSS.Trusted', true );

		$config->set( 'Attr.AllowedFrameTargets', array( '_blank', '_self', '_parent', '_top' ) );
		$config->set( 'HTML.Doctype', 'HTML 4.01 Transitional' );

		// Get CSS definitions.
		try {
			$css_definition = $config->getDefinition( 'CSS' );
		} catch ( HTMLPurifier_Exception $e ) {
			$css_definition = new stdClass();
		}

		// Add flexbox CSS.
		// Redefine the 'display' property to add the flex attribute.
		$css_definition->info['display']         = new HTMLPurifier_AttrDef_Enum(
			array(
				'inline',
				'block',
				'list-item',
				'run-in',
				'compact',
				'marker',
				'table',
				'inline-block',
				'inline-table',
				'table-row-group',
				'table-header-group',
				'table-footer-group',
				'table-row',
				'table-column-group',
				'table-column',
				'table-cell',
				'table-caption',
				'none',
				'flex',
			)
		);
		$css_definition->info['flex-direction']  = new HTMLPurifier_AttrDef_Enum(
			array(
				'column',
				'column-reverse',
				'row',
				'row-reverse',
			)
		);
		$css_definition->info['flex-wrap']       = new HTMLPurifier_AttrDef_Enum(
			array(
				'wrap',
				'nowrap',
				'wrap-reverse',
			)
		);
		$css_definition->info['justify-content'] = new HTMLPurifier_AttrDef_Enum(
			array(
				'center',
				'flex-start',
				'flex-end',
				'space-around',
				'space-between',
			)
		);
		$css_definition->info['align-items']     = new HTMLPurifier_AttrDef_Enum(
			array(
				'center',
				'flex-start',
				'flex-end',
				'stretch',
				'baseline',
			)
		);
		$css_definition->info['align-content']   = new HTMLPurifier_AttrDef_Enum(
			array(
				'space-between',
				'space-around',
				'stretch',
				'center',
				'flex-start',
				'flex-end',
			)
		);
		$css_definition->info['flex-basis']      = new HTMLPurifier_AttrDef_CSS_Percentage();

		return new HTMLPurifier( $config );
	}
}
