### Quick Start: Render Editor.js Output to HTML Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md Pass Editor.js's JSON output directly to the `make` method to render blocks into HTML. This is the most straightforward way to get started. ```php use BumpCore\EditorPhp\EditorPhp; // Passing Editor.js's output directly to the `make`. // This will render blocks into html. echo EditorPhp::make($json)->render(); ``` -------------------------------- ### Install Editor.php using Composer Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md Use this command to install the Editor.php package via Composer. ```bash composer require bumpcore/editor.php ``` -------------------------------- ### Parse, Manipulate, and Render Editor.js Output in PHP Source: https://context7.com/bumpcore/editor.php/llms.txt This example shows how to parse Editor.js JSON output, manipulate blocks (like adding classes to images or prefixing headers), extract specific content, and render the final HTML. It also demonstrates converting the modified content back to JSON or an array. ```php use BumpCore\EditorPhp\EditorPhp; use BumpCore\EditorPhp\Block\Block; use BumpCore\EditorPhp\Blocks\Paragraph; use BumpCore\EditorPhp\Blocks\Header; use BumpCore\EditorPhp\Blocks\Image; // Sample Editor.js output $json = '{ "time": 1672852569662, "blocks": [ { "type": "header", "data": { "text": "Getting Started with Editor.php", "level": 1 } }, { "type": "paragraph", "data": { "text": "Editor.php makes it easy to work with Editor.js output." } }, { "type": "image", "data": { "file": { "url": "https://example.com/image.jpg" }, "caption": "Sample Image", "withBorder": true, "stretched": false, "withBackground": false } }, { "type": "list", "data": { "style": "ordered", "items": [ "Parse JSON output", "Manipulate blocks", "Render to HTML" ] } } ], "version": "2.26.4" }'; // Set template framework EditorPhp::useTailwind(); // Parse the JSON $editor = EditorPhp::make($json); // Access metadata echo "Created: " . $editor->time->format('Y-m-d H:i:s') . "\n"; echo "Version: " . $editor->version . "\n"; echo "Blocks: " . $editor->blocks->count() . "\n"; // Process blocks $editor->blocks->transform(function(Block $block) { // Add CSS classes to images if ($block instanceof Image) { $block->set('customClass', 'rounded-lg shadow-md'); } // Prefix all headers if ($block instanceof Header && $block->get('level') === 1) { $block->set('text', '📚 ' . $block->get('text')); } return $block; }); // Extract specific content $headers = $editor->blocks ->filter(fn($b) => $b instanceof Header) ->map(fn($b) => $b->get('text')) ->toArray(); $images = $editor->blocks ->filter(fn($b) => $b instanceof Image) ->map(fn($b) => $b->get('file.url')) ->toArray(); // Render HTML output $html = $editor->render(); // Convert back to JSON (with modifications) $modifiedJson = $editor->toJson(JSON_PRETTY_PRINT); // Convert to array for API response $array = $editor->toArray(); echo $html; ``` -------------------------------- ### Convert EditorPhp to Array and JSON Source: https://context7.com/bumpcore/editor.php/llms.txt Use `toArray()` to get a PHP array representation or `toJson()` to get a JSON string. Options can be passed to `toJson()` for formatting. ```php use BumpCore\EditorPhp\EditorPhp; $editor = EditorPhp::make($json); // Modify some blocks $editor->blocks->transform(function($block) { if ($block instanceof \BumpCore\EditorPhp\Blocks\Paragraph) { $block->set('text', strip_tags($block->get('text'))); } return $block; }); // Convert to array $array = $editor->toArray(); // Returns: ['time' => 1672852569662, 'blocks' => [...], 'version' => '2.26.4'] // Convert to JSON string $json = $editor->toJson(); // With JSON options $prettyJson = $editor->toJson(JSON_PRETTY_PRINT); ``` -------------------------------- ### Access and Transform Blocks Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md Blocks are stored as an Illuminate\Support\Collection, allowing manipulation using collection methods. This example demonstrates stripping HTML tags from paragraph block text. ```php use BumpCore\EditorPhp\EditorPhp; use BumpCore\EditorPhp\Block\Block; use BumpCore\EditorPhp\Blocks\Paragraph; $editor = EditorPhp::make($json); // Stripping all tags from paragraph block's text. $editor->blocks->transform(function(Block $block) { if($block instanceof Paragraph) { $block->set('text', strip_tags($block->get('text'))); } return $block; }); ``` -------------------------------- ### Generate Fake JSON Data with EditorPhp Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md Use the `EditorPhp::fake()` method to generate fake JSON data. Optionally, pass `true` to get an `EditorPhp` instance with fake data, and specify min/max block lengths. ```php use BumpCore\EditorPhp\EditorPhp; // This will return a generated fake JSON. $fake = EditorPhp::fake(); // If we pass first argument true, it will return new `EditorPhp` instance with fake data. $fakeEditor = EditorPhp::fake(true); // You can also pass min lenght and max lenght of blocks. // Below code will generate blocks between 1 and 3. $fakeEditor = EditorPhp::fake(true, 1, 3); echo $fakeEditor->render(); ``` -------------------------------- ### Implement a Basic Custom Block Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md Create a new custom block by extending the base `Block` class and implementing the `render` method for its display logic. ```php use BumpCore\EditorPhp\Block\Block; class MyCustomBlock extends Block { public function render(): string { return view('blocks.my-custom-block', ['data' => $this->data]); } } ``` -------------------------------- ### Create EditorPhp Instance Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md Two methods are available for creating an instance of the EditorPhp class: using the `new` keyword or the static `make` method. Both achieve the same result. ```php use BumpCore\EditorPhp\EditorPhp; // Using the `new` syntax. $editor = new EditorPhp($json); // Using the `make` syntax. $editor = EditorPhp::make($json); ``` -------------------------------- ### Create New Block with Artisan Command Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md Use the `php artisan make:block ` command to generate a new block class, which will be placed in the `app/Blocks` directory. ```bash php artisan make:block CustomImageBlock ``` -------------------------------- ### Create EditorPhp Instance Source: https://context7.com/bumpcore/editor.php/llms.txt Parse Editor.js JSON output into a manageable EditorPhp object using either the static make() method or the constructor. ```php use BumpCore\EditorPhp\EditorPhp; // Editor.js JSON output $json = '{ "time": 1672852569662, "blocks": [ { "type": "header", "data": { "text": "Welcome to Editor.php", "level": 2 } }, { "type": "paragraph", "data": { "text": "This is a block-styled editor output." } } ], "version": "2.26.4" }'; // Using the static make() method $editor = EditorPhp::make($json); // Or using the constructor $editor = new EditorPhp($json); // Access properties echo $editor->time; // Carbon instance of the timestamp echo $editor->version; // "2.26.4" ``` -------------------------------- ### Switch Rendering Template Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md Editor.php supports 'tailwindcss' and 'Bootstrap 5' for block rendering. Use these static methods to switch between the default templates. ```php use BumpCore\EditorPhp\EditorPhp; // Using tailwind. EditorPhp::useTailwind(); // Using Bootstrap. EditorPhp::useBootstrapFive(); ``` -------------------------------- ### Extend EditorPhp with Custom Macros Source: https://context7.com/bumpcore/editor.php/llms.txt Demonstrates how to add custom methods (macros) to the EditorPhp class to filter and process blocks, such as retrieving all paragraphs, headers, images, plain text content, or calculating word count. Requires importing Block, Paragraph, Header, and Image classes. ```php use BumpCore\EditorPhp\EditorPhp; use BumpCore\EditorPhp\Block\Block; use BumpCore\EditorPhp\Blocks\Paragraph; use BumpCore\EditorPhp\Blocks\Header; use BumpCore\EditorPhp\Blocks\Image; // Register custom macros EditorPhp::macro('getParagraphs', function() { return $this->blocks->filter(fn(Block $block) => $block instanceof Paragraph); }); EditorPhp::macro('getHeaders', function() { return $this->blocks->filter(fn(Block $block) => $block instanceof Header); }); EditorPhp::macro('getImages', function() { return $this->blocks->filter(fn(Block $block) => $block instanceof Image); }); EditorPhp::macro('getPlainText', function() { return $this->blocks ->filter(fn(Block $block) => $block instanceof Paragraph || $block instanceof Header) ->map(fn(Block $block) => strip_tags($block->get('text', ''))) ->implode("\n\n"); }); EditorPhp::macro('wordCount', function() { $text = $this->getPlainText(); return str_word_count($text); }); // Usage $editor = EditorPhp::make($json); $paragraphs = $editor->getParagraphs(); // Collection of Paragraph blocks $headers = $editor->getHeaders(); // Collection of Header blocks $images = $editor->getImages(); // Collection of Image blocks $plainText = $editor->getPlainText(); // Plain text content $wordCount = $editor->wordCount(); // Total word count ``` -------------------------------- ### Access Time and Version from EditorPhp Instance Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md Retrieve the 'time' and 'version' properties directly from an `EditorPhp` instance. The 'time' property is a Carbon instance. ```php use BumpCore\EditorPhp\EditorPhp; $editor = EditorPhp::make($json); $editor->time; $editor->version; ``` -------------------------------- ### Generate Custom Editor.js Blocks with Artisan Source: https://context7.com/bumpcore/editor.php/llms.txt Create new custom block classes for Editor.js using the `make:block` Artisan command. This command generates a boilerplate file for your custom block, which you can then register with EditorPhp. ```bash # Create a new block class php artisan make:block CustomImageBlock # Creates: app/Blocks/CustomImageBlock.php ``` ```php // Generated file: app/Blocks/CustomImageBlock.php namespace App\Blocks; use BumpCore\EditorPhp\Block\Block; class CustomImageBlock extends Block { public function render(): string { return view('blocks.custom-image-block', ['data' => $this->data]); } } // Register in AppServiceProvider use BumpCore\EditorPhp\EditorPhp; public function boot(): void { EditorPhp::register([ 'customImage' => \App\Blocks\CustomImageBlock::class, ]); } ``` -------------------------------- ### Return Editor.php Instance as Response Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md An `EditorPhp` instance can be directly returned from a controller. It will automatically render as HTML or JSON based on the request's `Accept` header. ```php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Models\Post; class ShowPostController extends Controller { public function __invoke(Post $post) { // Depending on the request it will return json or rendered html. return $post->content; } } ``` -------------------------------- ### Access and Modify Block Data Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md Demonstrates various methods for accessing and modifying block data, including direct access via the data object, invoking the data object, and using shortcut methods. ```php public function render(): string { // ... // Method 1: Accessing through the data object. $data = $this->data; $data->get('custom.data'); $data->set('custom.data', 'Hello World!'); // Method 2: Accessing by invoking the data object. $data('custom.data'); // Hello World! // Method 3: Using shortcuts. $this->get('custom.data'); $this->set('custom.data', 'Nice!'); // ... } ``` -------------------------------- ### Register Custom Blocks in EditorPhp Source: https://context7.com/bumpcore/editor.php/llms.txt Extend EditorPhp by creating custom block classes that extend `BumpCore\EditorPhp\Block\Block`. Register these custom blocks using `EditorPhp::register()`. You can either add new blocks or override existing ones. ```php use BumpCore\EditorPhp\EditorPhp; use BumpCore\EditorPhp\Block\Block; // Create a custom block class class MyCustomBlock extends Block { public function render(): string { $title = $this->get('title', 'Default Title'); $content = $this->get('content', ''); return "

{$title}

{$content}

"; } public function rules(): array { return [ 'title' => 'required|string|max:255', 'content' => 'required|string', ]; } } // Register custom blocks (merges with existing blocks) EditorPhp::register([ 'customBlock' => MyCustomBlock::class, 'paragraph' => \App\Blocks\MyParagraph::class, // Override default ]); // Or override all registered blocks EditorPhp::register([ 'paragraph' => \App\Blocks\MyParagraph::class, 'header' => \App\Blocks\MyHeader::class, ], true); // true = override mode ``` -------------------------------- ### Process Custom Image Block Uploads Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md Iterate through editor blocks and invoke the `upload` method on instances of `MyImageBlock` to finalize the image upload process. ```php use BumpCore\EditorPhp\EditorPhp; use Blocks\MyImageBlock; $editor = EditorPhp::make($json); $editor->blocks->each(function(Block $block) { if ($block instanceof MyImageBlock) { $block->upload(); } }); return $editor->toJson(); ``` -------------------------------- ### Render EditorPhp Instance to HTML Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md The EditorPhp instance can be rendered to HTML using the `render` function, the `toHtml` function, or by directly casting the object to a string. All methods produce the same output. ```php use BumpCore\EditorPhp\EditorPhp; $editor = EditorPhp::make($json); // Using the `render` function. echo $editor->render(); // Using the `toHtml` function. echo $editor->toHtml(); // Or by casting to a string. echo $editor; ``` -------------------------------- ### Sanitize Block Data with Allowed Tags and Attributes Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md Define allowed HTML tags and attributes in the `allow` method to sanitize block data and prevent injection vulnerabilities. ```php use BumpCore\EditorPhp\Block\Block; class MyCustomBlock extends Block { // ... public function allow(): array|string { // Specifying one by one. return [ 'text' => [ 'a:href,target,title', // Will allow `a` tag and href, target, and title attributes. 'b', // Will only allow `b` tag with no attributes. ], 'items.*.name' => 'b:*', // Will allow `b` tag with all attributes. 'items.*.html' => '*', // Will allow every tag and every attribute. ]; // Or just allowing all attributes and tags for all data. return '*'; } // ... } ``` -------------------------------- ### Extend Image Block with Custom Upload Logic Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md Extend the Image block to implement custom temporary and final upload logic. The `uploadTemp` method handles temporary file storage, while `upload` manages the final processing and data updates. ```php use BumpCore\EditorPhp\Blocks\Image; class MyImageBlock extends Image { public static function uploadTemp(string $fileName = 'image'): array { // ... // Temporary upload logic. return [ 'success' => ..., 'file' => [ 'url' => ... ], ]; } public function upload(): void { $file = $this->get('file.url'); // Your logic. // ... // Altering the current block's data. $this->set('file.url', ...); } } // ... // Registering customized block. EditorPhp::register([ 'image' => MyImageBlock::class ]); ``` -------------------------------- ### Generate Fake Editor.js Data Source: https://context7.com/bumpcore/editor.php/llms.txt Use `EditorPhp::fake()` to generate mock JSON strings or EditorPhp instances. Control the number of blocks generated and customize fake data for custom blocks by extending the `Block` class and implementing a static `fake` method. ```php use BumpCore\EditorPhp\EditorPhp; use BumpCore\EditorPhp\Block\Block; // Generate fake JSON string $fakeJson = EditorPhp::fake(); // Generate fake EditorPhp instance $fakeEditor = EditorPhp::fake(true); echo $fakeEditor->render(); // Control number of blocks (min: 1, max: 5) $fakeEditor = EditorPhp::fake(true, 1, 5); ``` ```php class MyBlock extends Block { public static function fake(\Faker\Generator $faker): array { $items = []; foreach (range(0, $faker->numberBetween(1, 5)) as $i) { $items[] = [ 'name' => $faker->name(), 'email' => $faker->email(), ]; } return [ 'title' => $faker->sentence(), 'description' => $faker->paragraph(), 'items' => $items, 'isActive' => $faker->boolean(), ]; } public function render(): string { return "
{$this->get('title')}
"; } } // Now EditorPhp::fake() will include MyBlock in generated data ``` -------------------------------- ### Register and Use Custom Alert Block in Editor.php Source: https://context7.com/bumpcore/editor.php/llms.txt Defines a custom 'AlertBlock' with validation rules, allowed HTML tags, rendering logic, and a fake data generator. It is then registered with EditorPhp and used to render JSON content. ```php use BumpCore\EditorPhp\Block\Block; use BumpCore\EditorPhp\EditorPhp; class AlertBlock extends Block { public function rules(): array { return [ 'type' => 'required|in:info,warning,error,success', 'title' => 'required|string|max:100', 'message' => 'required|string|max:500', 'dismissible' => 'boolean', ]; } public function allows(): array|string { return [ 'title' => ['b', 'strong', 'em'], 'message' => [ 'a:href,target', 'b', 'strong', 'em', 'code', ], ]; } public function render(): string { $type = $this->get('type', 'info'); $title = $this->get('title'); $message = $this->get('message'); $dismissible = $this->get('dismissible', false); $colors = [ 'info' => 'bg-blue-100 border-blue-500 text-blue-700', 'warning' => 'bg-yellow-100 border-yellow-500 text-yellow-700', 'error' => 'bg-red-100 border-red-500 text-red-700', 'success' => 'bg-green-100 border-green-500 text-green-700', ]; $classes = $colors[$type] ?? $colors['info']; $dismissBtn = $dismissible ? '' : ''; return << {$dismissBtn}

{$title}

{$message}

HTML; } public static function fake(\Faker\Generator $faker): array { return [ 'type' => $faker->randomElement(['info', 'warning', 'error', 'success']), 'title' => $faker->sentence(3), 'message' => $faker->paragraph(), 'dismissible' => $faker->boolean(), ]; } } // Register and use EditorPhp::register(['alert' => AlertBlock::class]); $json = '{ "time": 1672852569662, "blocks": [ { "type": "alert", "data": { "type": "warning", "title": "Important Notice", "message": "Please read the documentation carefully.", "dismissible": true } } ], "version": "2.26.4" }'; echo EditorPhp::make($json)->render(); ``` -------------------------------- ### Laravel HTTP Response for Editor.js Source: https://context7.com/bumpcore/editor.php/llms.txt Return EditorPhp instances directly from controllers. The response format (JSON or HTML) is automatically determined by the request's `Accept` header, making it suitable for both API and browser clients. ```php namespace App\Http\Controllers; use App\Models\Post; use BumpCore\EditorPhp\EditorPhp; use Illuminate\Http\Request; class PostController extends Controller { public function show(Request $request, Post $post) { // Returns JSON if request expects JSON (API calls) // Returns rendered HTML otherwise (browser requests) return $post->content; } public function api(Post $post) { // Force JSON response return response()->json($post->content->toArray()); } public function preview(Request $request) { // Preview Editor.js content before saving $editor = EditorPhp::make($request->input('content')); return $editor; // Auto-responds with JSON or HTML } } // API route returns: // { // "time": 1672852569662, // "blocks": [...], // "version": "2.26.4" // } // Browser route returns rendered HTML ``` -------------------------------- ### Generate Fake Data for Custom Block Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md Add a static `fake` method to your custom block class to enable fake data generation for that block when using Editor.php. ```php use BumpCore\EditorPhp\Block\Block; class MyCustomBlock extends Block { // ... public static function fake(\Faker\Generator $faker): array { $items = []; foreach (range(0, $faker->numberBetween(0, 10)) as $index) { $items[] = [ 'name' => fake()->name(), 'html' => $faker->randomHtml(), ]; } return [ 'text' => fake()->text(255), 'items' => $items, ]; } // ... } ``` -------------------------------- ### Check for Block Data Existence Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md Utilize `has` method on the data object or the block instance to check if a specific data key exists. ```php $data->has('custom.data'); // or $this->has('custom.data'); ``` -------------------------------- ### Extend Built-in Image Block for Custom Uploads Source: https://context7.com/bumpcore/editor.php/llms.txt Extend the `Image` block to implement custom upload logic. Use a static method for temporary uploads and an instance method for processing and moving files to permanent storage. Register the custom block with `EditorPhp::register()`. ```php use BumpCore\EditorPhp\EditorPhp; use BumpCore\EditorPhp\Blocks\Image; use BumpCore\EditorPhp\Block\Block; class MyImageBlock extends Image { // Static method for temporary uploads (API endpoint) public static function uploadTemp(string $fileName = 'image'): array { $file = request()->file($fileName); $path = $file->store('temp/images', 'public'); return [ 'success' => 1, 'file' => [ 'url' => asset('storage/' . $path), ], ]; } // Instance method for final upload processing public function upload(): void { $tempUrl = $this->get('file.url'); // Move from temp to permanent storage $permanentUrl = $this->moveToPermament($tempUrl); // Update the block data $this->set('file.url', $permanentUrl); } private function moveToPermament(string $tempUrl): string { // Your upload logic here return str_replace('temp/', 'images/', $tempUrl); } } // Register the custom image block EditorPhp::register(['image' => MyImageBlock::class]); // Process uploads when saving $editor = EditorPhp::make($json); $editor->blocks->each(function(Block $block) { if ($block instanceof MyImageBlock) { $block->upload(); } }); // Save the updated JSON $finalJson = $editor->toJson(); ``` -------------------------------- ### Render Editor.js Content to HTML Source: https://context7.com/bumpcore/editor.php/llms.txt Render Editor.js content to HTML using the render() or toHtml() methods. The output can be cast directly to a string. Templates can be switched between Tailwind CSS and Bootstrap 5. ```php use BumpCore\EditorPhp\EditorPhp; $editor = EditorPhp::make($json); // Using the render() method echo $editor->render(); // Using toHtml() method echo $editor->toHtml(); // Or cast directly to string echo $editor; // Switch between template frameworks EditorPhp::useTailwind(); // Use Tailwind CSS templates (default) EditorPhp::useBootstrapFive(); // Use Bootstrap 5 templates // Check current template $template = EditorPhp::usingTemplate(); // Returns 'tailwind' or 'bootstrap-five' ``` -------------------------------- ### Register and Use Custom Macros in EditorPhp Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md Define and use custom macros with `EditorPhp::macro()`. Macros allow you to extend the functionality of the editor instance, similar to Laravel's macroable traits. ```php use BumpCore\EditorPhp\EditorPhp; // Registering new macro. EditorPhp::macro( 'getParagraphs', fn () => $this->blocks->filter(fn (Block $block) => $block instanceof Paragraph) ); $editor = EditorPhp::make($json); // This will return a collection that only contains paragraphs. $paragraphs = $editor->getParagraphs(); ``` -------------------------------- ### Register Custom Blocks in EditorPhp Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md Register custom block classes with `EditorPhp::register()`. You can choose to merge new blocks with existing ones or override them completely by passing `true` as the second argument. ```php use BumpCore\EditorPhp\EditorPhp; // This will merge without erasing already registered blocks. Other blocks will still remain with the recently registered `image` and `paragraph` blocks. EditorPhp::register([ 'image' => \Blocks\MyCustomImageBlock::class, 'paragraph' => \Blocks\MyCustomParagraphBlock::class, ]); // This will override already registered blocks. We now only have `image` and `paragraph` blocks. EditorPhp::register([ 'image' => \Blocks\MyCustomImageBlock::class, 'paragraph' => \Blocks\MyCustomParagraphBlock::class, ], true); ``` -------------------------------- ### Access and Modify Block Data Source: https://context7.com/bumpcore/editor.php/llms.txt Access and modify block data using dot notation through the `Data` object or block shortcuts. Data can be retrieved, set, or checked for existence. ```php use BumpCore\EditorPhp\EditorPhp; use BumpCore\EditorPhp\Block\Block; $editor = EditorPhp::make($json); $editor->blocks->each(function(Block $block) { // Method 1: Using the data object directly $data = $block->data; $text = $data->get('text'); $data->set('text', 'Modified text'); // Method 2: Invoking the data object $text = $data('text'); // Method 3: Using block shortcuts (recommended) $text = $block->get('text'); $block->set('text', 'New text'); // Check if data exists if ($block->has('caption')) { echo $block->get('caption'); } // Access nested data with dot notation $imageUrl = $block->get('file.url'); $block->set('file.url', 'https://example.com/new-image.jpg'); }); ``` -------------------------------- ### Convert EditorPhp Instance to Array Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md Convert an `EditorPhp` instance to an associative array using the `toArray()` method. This is useful for inspecting or further processing the editor's content. ```php use BumpCore\EditorPhp\EditorPhp; $editor = EditorPhp::make($json); // This will return ['time' => ..., 'blocks' => [...], 'version' => '...'] $array = $editor->toArray(); ``` -------------------------------- ### Define Validation Rules for Block Data Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md Implement the `rules` method within a custom block to define validation criteria for its data, leveraging Laravel's validation library. ```php use BumpCore\EditorPhp\Block\Block; class MyCustomBlock extends Block { // ... public function rules(): array { return [ 'text' => 'required|string|max:255', 'items' => 'sometimes|array', 'items.*.name' => 'required|string|max:255', 'items.*.html' => 'required|string|min:255', ]; } // ... } ``` -------------------------------- ### Render Editor.php Instance in Blade View Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md An `EditorPhp` instance can be directly embedded within a Blade template using double curly braces for rendering. ```blade {{-- blog.show.blade.php --}}

{{ $post->title }}

{{ $post->content }}
``` -------------------------------- ### Access Model Instance within a Block Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md When using `EditorPhpCast`, you can access the parent model instance via `$this->root->model` within your block's methods. ```php use BumpCore\EditorPhp\Block\Block; use App\Models\Post; class MyBlock extends Block { // ... public static function render(): string { if($this->root->model instanceof Post) { // Do the other thing. } } // ... } ``` -------------------------------- ### Convert EditorPhp Instance to JSON Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md Encode an `EditorPhp` instance into a JSON string using the `toJson()` method. This method accepts standard JSON encoding options. ```php use BumpCore\EditorPhp\EditorPhp; $editor = EditorPhp::make($json); // This will return encoded JSON. $json = $editor->toJson(JSON_PRETTY_PRINT); ``` -------------------------------- ### Eloquent Cast for Editor.js Content Source: https://context7.com/bumpcore/editor.php/llms.txt Use EditorPhpCast to automatically cast model attributes to EditorPhp instances. This simplifies handling Editor.js content within your Eloquent models, enabling programmatic manipulation and automatic JSON conversion. ```php use BumpCore\EditorPhp\Casts\EditorPhpCast; use Illuminate\Database\Eloquent\Model; class Post extends Model { protected $casts = [ 'content' => EditorPhpCast::class, ]; } // Usage in controller class PostController extends Controller { public function show(Post $post) { // $post->content is automatically an EditorPhp instance return view('posts.show', ['post' => $post]); } public function store(Request $request) { $post = Post::create([ 'title' => $request->title, 'content' => $request->content, // Raw JSON from Editor.js ]); return redirect()->route('posts.show', $post); } public function update(Request $request, Post $post) { // Modify content programmatically $editor = $post->content; $editor->blocks->transform(function($block) { // Process blocks return $block; }); $post->content = $editor; // Cast handles JSON conversion $post->save(); return redirect()->route('posts.show', $post); } } // Access model from within blocks class MyBlock extends Block { public function render(): string { // Access the parent model if using cast if (isset($this->root->model)) { $model = $this->root->model; $authorName = $model->author->name ?? 'Unknown'; return "

By: {$authorName}

"; } return "

{$this->get('text')}

"; } } ``` -------------------------------- ### Define Validation Rules for EditorPhp Blocks Source: https://context7.com/bumpcore/editor.php/llms.txt Implement the `rules()` method in your custom block class to define validation rules using Laravel's validation syntax. This ensures data integrity for block content. Invalid blocks will have empty data. ```php use BumpCore\EditorPhp\Block\Block; class ValidatedBlock extends Block { public function rules(): array { return [ 'text' => 'required|string|max:1000', 'level' => 'integer|min:1|max:6', 'items' => 'sometimes|array', 'items.*.name' => 'required|string|max:255', 'items.*.url' => 'required|url', 'file.url' => 'required|url', 'withBorder' => 'boolean', ]; } public function render(): string { // If validation fails, $this->data will be empty if (!$this->has('text')) { return ''; // Skip rendering invalid blocks } return "

{$this->get('text')}

"; } } // Usage $editor = EditorPhp::make($json); // Blocks with invalid data will have empty data arrays ``` -------------------------------- ### Cast Model Attribute to Editor.php Instance Source: https://github.com/bumpcore/editor.php/blob/1.x/README.md Use `EditorPhpCast` in your Eloquent model's `$casts` property to automatically cast a database attribute to an `EditorPhp` instance. ```php use BumpCore\EditorPhp\Casts\EditorPhpCast; use Illuminate\Database\Eloquent\Model; class Post extends Model { protected $casts = [ 'content' => EditorPhpCast::class, ]; } // ... $post = Post::find(1); // Content is `EditorPhp` instance in here. echo $post->content->render(); ``` -------------------------------- ### Manipulate Editor.js Blocks Source: https://context7.com/bumpcore/editor.php/llms.txt Access and manipulate blocks using Laravel collection methods. Blocks can be transformed, filtered, or accessed individually. ```php use BumpCore\EditorPhp\EditorPhp; use BumpCore\EditorPhp\Block\Block; use BumpCore\EditorPhp\Blocks\Paragraph; use BumpCore\EditorPhp\Blocks\Header; $editor = EditorPhp::make($json); // Access all blocks $blocks = $editor->blocks; // Transform paragraph text by stripping HTML tags $editor->blocks->transform(function(Block $block) { if ($block instanceof Paragraph) { $block->set('text', strip_tags($block->get('text'))); } return $block; }); // Filter to get only header blocks $headers = $editor->blocks->filter(fn(Block $block) => $block instanceof Header); // Get the first paragraph $firstParagraph = $editor->blocks->first(fn(Block $block) => $block instanceof Paragraph); // Count blocks by type $paragraphCount = $editor->blocks->filter(fn(Block $block) => $block instanceof Paragraph)->count(); ``` -------------------------------- ### Render Editor.js Content in Laravel Blade Views Source: https://context7.com/bumpcore/editor.php/llms.txt Easily render Editor.js content within your Blade templates. You can render the entire content, iterate over specific block types, or generate elements like a table of contents from header blocks. ```blade {{-- resources/views/posts/show.blade.php --}}

{{ $post->title }}

{{-- Renders all blocks as HTML --}}
{{ $post->content }}
{{-- Or use explicit render --}}
{!! $post->content->render() !!}
{{-- Iterate over specific block types --}} {{-- Table of contents from headers --}} ``` -------------------------------- ### Sanitize HTML in EditorPhp Block Data Source: https://context7.com/bumpcore/editor.php/llms.txt Use the `allows()` method in your custom block class to control which HTML tags and attributes are permitted within block data, preventing XSS attacks. You can specify allowed tags and attributes per field or globally. ```php use BumpCore\EditorPhp\Block\Block; class SafeParagraph extends Block { public function allows(): array|string { return [ // Allow specific tags with specific attributes 'text' => [ 'a:href,target,title', // with href, target, title attributes 'b', // with no attributes 'strong', 'em', 'i', 'code', 'mark', ], // Allow all tags and attributes for a field 'rawHtml' => '*', // Allow tag with all attributes 'caption' => 'span:*', // Strip all HTML from this field 'plainText' => [], ]; } public function rules(): array { return [ 'text' => 'string', 'rawHtml' => 'string', 'caption' => 'string', 'plainText' => 'string', ]; } public function render(): string { return "

{$this->get('text')}

"; } } // Allow all tags and attributes for entire block class UnsanitizedBlock extends Block { public function allows(): array|string { return '*'; // No sanitization } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.