jcicero518
6/20/2018 - 10:41 PM

Laravel CkEditor Provider

Laravel CkEditor Provider

<?php
public function register() {
  /**
		 * Register singleton for CkEditor provider class. Checks user input against
		 * an array of allowed HTML tags for rich text editors
		 */
		$this->app->singleton( CkEditor::class, function( $params = [] ) {
			$attrs = isset( $params['content'] ) ? $params['content'] : '';

			// config in Illuminate\Config\Repository
			$instance = new CkEditor( config( 'ckeditor.allowed_tags') );
			$instance->limitTags( $attrs );

			return $instance->getLimitedContent();
		});
}
<?php

namespace App\Editors;

use Exception;

class CkEditor {

	protected $tags;
	protected $instance;
	protected $limited_tags;
	protected $limited_content;

	public function __construct( $tags ) {
		$this->tags = $tags;
	}

	public function __toString() {
		return (string)$this->getTags();
	}

	/**
	 * Get string representation of tags to strip out
	 * from ckeditor config
	 *
	 * @return string
	 */
	public function getTags() : string {
		return implode('', $this->tags );
	}

	/**
	 * @return mixed
	 */
	public function getLimitedTags() {
		return $this->limited_tags;
	}

	public function limitTags( $attrValue ) {
		if ( ! is_string( $attrValue ) ) {
			throw new Exception( 'Attribute value must be a string' );
		}

		$this->limited_content = strip_tags( $attrValue, $this->getLimitedTags() );
	}

	public function getLimitedContent() {
		return $this->limited_content;
	}
}