wikimedia/zest-css
Composer 安装命令:
composer require wikimedia/zest-css
包简介
Fast, lightweight, extensible CSS selector engine for PHP
README 文档
README
zest.php is a fast, lightweight, extensible CSS selector engine for PHP.
Zest was designed to be very concise while still supporting CSS3/CSS4 selectors and remaining fast.
This is a port to PHP of the zest.js selector library. Since that project hasn't been updated in a while, bugfixes have been taken from the copy of zest included in the domino DOM library.
Report issues on Phabricator.
Usage
use Wikimedia\Zest\Zest; $els = Zest::find('section! > div[title="hello" i] > :local-link /href/ h1', $doc);
Install
This package is available on Packagist:
$ composer require wikimedia/zest-css
API
Functions below which take an opts array can be passed additional options
which affect match results. This are available from within custom selectors
(see below). At the moment, the standard selectors support the following
options:
standardsMode(bool): if present and true, various PHP workarounds will be disabled in favor of calling methods defined in web standards.getElementsById(true|callable(DOMNode,string):array<DOMElement>): if set totruethen an optimization will be disabled to ensure that Zest can return multiple elements for ID selectors if IDs are not unique in the document. If set to acallablethat takes a context node and an ID string and returns an array of Elements, a third-party DOM implementation can support an efficient index allowing multiple elements to share the same ID.
All methods will throw the exception returned by
ZestInst::newBadSelectorException() (by default, a new
InvalidArgumentException) if the selector fails to parse.
Zest::find( string $selector, $context, array $opts = [] ): array
This is equivalent to the standard
DOM method ParentNode#querySelectorAll().
Zest::matches( $element, string $selector, array $opts = [] ): bool
This is equivalent to the standard
DOM method Element#matches().
Since the PHP implementations of
DOMDocument::getElementById
and
DOMDocument#getElementsByTagName
have some performance and spec-compliance issues, Zest also exports useful
performant and correct versions of these:
Zest::getElementsById( $contextNode, string $id, array $opts = [] ): array
This is equivalent to the standard DOM method
Document#getElementById()
(although you can use any context node, not just the top-level document).
In addition, with the proper support from the DOM implementation, this can
return more than one matching element.
Zest::getElementsByTagName( $contextNode, string $tagName, array $opts = [] ): array
This is equivalent to the standard DOM method Element#getElementsByTagName(),
although you can use a DocumentFragment as the $contextNode.
Compatibility with alternative DOM implementations
Although the phpdoc declares \DOMNode, \DOMElement, etc as types,
these are not enforced by type hints and so Zest will work with any
standards-compliant DOM implementation (see the standardsMode
option flag above). This includes the new \Dom\Document classes
in PHP 8.4, for which Zest defines appropriate workarounds for
correct function.
Extension
It is possible to add your own selectors, operators, or combinators.
These are added to an instance of ZestInst, so they don't affect other
instances of Zest or the static Zest::find/Zest::matches methods.
The ZestInst class has non-static versions of all the static methods
available on Zest.
Adding a simple selector
Adding simple selectors is fairly straight forward. Only the addition of pseudo classes and attribute operators is possible. (Adding your own "style" of selector would require changes to the core logic.)
Here is an example of a custom :name selector which will match for an
element's name attribute: e.g. h1:name(foo). Effectively an alias
for h1[name=foo].
use Wikimedia\Zest\ZestInst; $z = new ZestInst; $z->addSelector1( ':name', function( string $param ):callable { return function ( $el, array $opts ) use ( $param ):bool { if ($el->getAttribute('name') === $param) return true; return false; }; } ); // Use it! $z->find( 'h1:name(foo)', $document );
If you wish to add selectors which depend on global properties (such as
:target) you can add the global information to $opts and it will be
made available when your selector function is called.
NOTE: if your pseudo-class does not take a parameter, use addSelector0.
Adding an attribute operator
$z = new ZestInst; // `$attr` is the attribute // `$val` is the value to match $z->addOperator( '!=', function( string $attr, string $val ):bool { return $attr !== $val; } ); // Use it! $z->find( 'h1[name != "foo"]', $document );
Adding a combinator
Adding a combinator is a bit trickier. It may seem confusing at first because the logic is upside-down. Zest interprets selectors from right to left.
Here is an example how a parent combinator could be implemented:
$z = new ZestInst; $z->addCombinator( '<', function( callable $test ): callable { return function( $el, array $opts ) use ( $test ): ?DOMNode { // `$el` is the current element $el = $el->firstChild; while ($el) { // return the relevant element // if it passed the test if ($el->nodeType === 1 && call_user_func($test, $el, $opts)) { return $el; } $el = $el->nextSibling; } return null; }; } ); // Use it! $z->find( 'h1 < section', $document );
The $test function tests whatever simple selectors it needs to look for, but
it isn't important what it does. The most important part is that you return
the relevant element once it's found.
Extension: JSON-valued attribute operators
One CSS extension included in Zest allows operating on JSON-valued attributes using JQ syntax. This is useful for documents that embed structured data in attributes, such as the MediaWiki DOM Spec.
You will need to require the wikimedia/zest-jq package in order
to use this extension; this is a
suggested package
and a
dev requirement
but not a runtime dependency of wikimedia/zest-css itself.
To enable the extension:
use Wikimedia\Zest\ZestJQ; $z = ZestJQ::register(new ZestInst);
You can also use the ZestJQ singleton, as shown below.
The syntax [attr/jq] parses the contents of the attribute attr as
a JSON string and evaluates the JQ expression jq against it. The
element matches if the expression evaluates to a non-empty or true
result.
use Wikimedia\Zest\ZestJQ; // Match all {{Citation needed}} transclusion markers in a MediaWiki document $els = ZestJQ::find( '[typeof="mw:Transclusion"]' . '[data-mw/.parts[].template?.target.href == "./Template:Citation_needed"]', $doc ); // Match elements whose data-mw JSON contains a `parserfunction` key anywhere // in the parts array (path-only query: matches if the path yields any value) // https://www.mediawiki.org/wiki/Parsoid/MediaWiki_DOM_spec/Parser_Functions $els = ZestJQ::find( '[data-mw/.parts[].parserfunction?]', $doc );
Tests
$ composer test
License and Credits
The original zest codebase is (c) Copyright 2011-2012, Christopher Jeffrey.
The port to PHP was initially done by C. Scott Ananian and is (c) Copyright 2019 Wikimedia Foundation.
Additional code and functionality is (c) Copyright 2020-2021 Wikimedia Foundation.
Both the original zest codebase and this port are distributed under the MIT license; see LICENSE for more info.
wikimedia/zest-css 适用场景与选型建议
wikimedia/zest-css 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 688.64k 次下载、GitHub Stars 达 4, 最近一次更新时间为 2019 年 03 月 13 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「css」 「engine」 「selector」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 wikimedia/zest-css 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 wikimedia/zest-css 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 wikimedia/zest-css 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
A Twig extension to insert css as inline styles with a tag
Caching and compression for Twig assets (JavaScript and CSS).
Contao 4 Css Style Selector bundle
A SilverStripe module to optimise the Meta, crawling, indexing, and sharing of your website content (forked from Cyber-Duck/Silverstripe-SEO)
A fieldtype that allows you to select a template from a dropdown.
A Processor for Markup written in PHP. Allows extraction of Markup into a data structure, orchestrated nested manipulation of said structure, and output as (optimized) Markup.
统计信息
- 总下载量: 688.64k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 4
- 点击次数: 25
- 依赖项目数: 2
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2019-03-13