mix8872 / editor.js
Editor.js的PHP后端实现
Requires
- php: >=5.6
- ezyang/htmlpurifier: ^4.8
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.13
- phpunit/phpunit: 5.4.*
This package is auto-updated.
Last update: 2024-09-13 15:33:30 UTC
README
Editor.js的服务端实现示例。它包含数据验证、HTML清理并将Editor.js的输出转换为Block对象。
安装
要安装库,请使用composer
composer require codex-team/editor.js:dev-master
指南
在您的PHP脚本顶部添加此行
use \EditorJS\EditorJS;
此行允许您获取具有以下方法的编辑器类
getBlocks
- 返回已清理的块数组
基本用法
您可以从编辑器获取数据并将其作为参数发送到编辑器的服务器验证器,如下所示
try { // Initialize Editor backend and validate structure $editor = new EditorJS( $data, $configuration ); // Get sanitized blocks (according to the rules from configuration) $blocks = $editor->getBlocks(); } catch (\EditorJSException $e) { // process exception }
Editor.js构造函数有以下参数
$data
— 从CodeX Editor前端获取数据的JSON字符串。
$configuration
— CodeX Editor工具配置的JSON字符串(见下文示例)。
配置文件
您可以为不同类型的Editor.js工具(标题、段落、列表、引用等)手动配置验证规则。您还可以通过添加新工具来扩展配置。
示例验证规则集
{
"tools": {
"header": {
"text": {
"type": "string",
"required": true,
"allowedTags": "b,i,a[href]"
},
"level": {
"type": "int",
"canBeOnly": [2, 3, 4]
}
}
}
}
其中
tools
— 支持的Editor.js工具数组。
header
— 定义header
工具设置。
text
和level
— header
工具结构中的参数。
text
是一个必需的 字符串,将除了b、i和a[href]标签外进行清理。
level
是一个可选的 整数,可以是0、1或2。
allowedTags
参数应遵循HTMLPurifier格式。
每个块有三个常见参数
type
(必需) — 块的类型
allowedTags
(可选) — 不会删除的字符串中的HTML标签
其他值可按照HTMLPurifier格式允许。
示例
"paragraph": {
"text": {
"type": "string",
"allowedTags": "i,b,u,a[href]"
}
}
canBeOnly
(可选) — 定义允许值集合
示例
"quote": {
"text": {
"type": "string"
},
"caption": {
"type": "string"
},
"alignment": {
"type": "string",
"canBeOnly": ["left", "center"]
}
}
简短设置语法
增加了一些语法糖。
工具设置可以是字符串
。它定义了工具的类型和默认设置。
"header": { "text": "string", "level": "int" }
它评估为
"header": { "text": { "type": "string", "allowedTags": "", "required": true }, "level": { "type": "int", "allowedTags": "", "required": true } }
工具设置可以是数组
。它定义了一个未经清理的允许值集合。
"quote": { "alignment": ["left", "center"], "caption": "string" }
它评估为
"quote": { "alignment": { "type": "string", "canBeOnly": ["left", "center"] }, "caption": { "type": "string", "allowedTags": "", "required": true } }
另一个配置示例:/tests/samples/syntax-sugar.json
嵌套工具
工具可以包含嵌套值。这是使用数组
类型实现的。
假设JSON输入如下
{
"blocks": [
"type": list,
"data": {
"items": [
"first", "second", "third"
],
"style": {
"background-color": "red",
"font-color": "black"
}
}
]
}
我们可以在配置中定义对此输入的验证规则
"list": {
"items": {
"type": "array",
"data": {
"-": {
"type": "string",
"allowedTags": "i,b,u"
}
}
},
"style": {
"type": "array",
"data": {
"background-color": {
"type": "string",
"canBeOnly": ["red", "blue", "green"]
},
"font-color": {
"type": "string",
"canBeOnly": ["black", "white"]
}
}
}
}
其中data
是数组值的容器,而-
是如果数组是顺序的,值的一个特殊快捷方式。
另一个配置示例:/tests/samples/test-config.json
异常
EditorJS类
BlockHandler类
ConfigLoader类
制作工具
如果您在客户端连接了新的工具,那么您应该为该工具创建一个配置规则,以便在服务器端进行验证。
仓库
https://github.com/codex-editor/editorjs-php/
关于CodeX
我们是一个由位于俄罗斯圣彼得堡的IFMO学生和毕业生组成的Web开发爱好者小团队。欢迎您通过team@ifmo.su给我们反馈。