From 121c35737d58b9670df6010b7c5ff06cd6aad8f0 Mon Sep 17 00:00:00 2001 From: Javier Casares Date: Wed, 4 Nov 2026 17:27:19 +0000 Subject: [PATCH] v1.2.3 --- changelog.txt | 42 ++ readme.txt | 60 +- ...tstxt-documentation-markdown-functions.php | 16 +- robotstxt-documentation-markdown-map.php | 3 +- robotstxt-documentation-markdown.php | 40 +- uninstall.php | 28 +- vendor/autoload.php | 2 +- vendor/composer/autoload_classmap.php | 4 - vendor/composer/autoload_psr4.php | 2 +- vendor/composer/autoload_real.php | 10 +- vendor/composer/autoload_static.php | 15 +- vendor/composer/installed.json | 103 ++-- vendor/composer/installed.php | 30 +- vendor/composer/platform_check.php | 4 +- vendor/league/commonmark/CHANGELOG.md | 59 +- vendor/league/commonmark/README.md | 2 +- .../Extension/Autolink/UrlAutolinkParser.php | 9 +- .../Parser/Block/ListBlockStartParser.php | 2 +- .../DisallowedRawHtmlRenderer.php | 6 +- .../ExternalLink/ExternalLinkProcessor.php | 28 +- .../Renderer/FootnoteBackrefRenderer.php | 8 +- .../Footnote/Renderer/FootnoteRefRenderer.php | 8 +- .../HeadingPermalinkProcessor.php | 4 + .../InlinesOnly/InlinesOnlyExtension.php | 1 + .../src/Extension/Table/TableParser.php | 37 +- .../src/Extension/Table/TableStartParser.php | 32 +- .../TaskList/TaskListItemMarkerParser.php | 5 +- .../Block/BlockContinueParserInterface.php | 6 +- .../src/Reference/ReferenceParser.php | 12 +- .../commonmark/src/Util/ArrayCollection.php | 2 + .../commonmark/src/Util/LinkParserHelper.php | 4 +- .../commonmark/src/Util/RegexHelper.php | 4 +- vendor/nette/schema/composer.json | 24 +- vendor/nette/schema/readme.md | 9 +- vendor/nette/schema/src/Schema/Context.php | 44 +- .../schema/src/Schema/DynamicParameter.php | 4 +- .../schema/src/Schema/Elements/AnyOf.php | 46 +- .../nette/schema/src/Schema/Elements/Base.php | 77 +-- .../schema/src/Schema/Elements/Structure.php | 101 ++-- .../nette/schema/src/Schema/Elements/Type.php | 68 +-- vendor/nette/schema/src/Schema/Expect.php | 72 +-- vendor/nette/schema/src/Schema/Helpers.php | 125 ++-- vendor/nette/schema/src/Schema/Message.php | 60 +- vendor/nette/schema/src/Schema/Processor.php | 53 +- vendor/nette/schema/src/Schema/Schema.php | 20 +- .../schema/src/Schema/ValidationException.php | 27 +- vendor/nette/utils/composer.json | 15 +- vendor/nette/utils/readme.md | 2 +- vendor/nette/utils/src/HtmlStringable.php | 5 +- .../utils/src/Iterators/CachingIterator.php | 33 +- vendor/nette/utils/src/Iterators/Mapper.php | 5 +- vendor/nette/utils/src/SmartObject.php | 3 - vendor/nette/utils/src/StaticClass.php | 12 +- vendor/nette/utils/src/Translator.php | 2 +- vendor/nette/utils/src/Utils/ArrayHash.php | 9 +- vendor/nette/utils/src/Utils/ArrayList.php | 19 +- vendor/nette/utils/src/Utils/Arrays.php | 87 ++- vendor/nette/utils/src/Utils/Callback.php | 29 +- vendor/nette/utils/src/Utils/DateTime.php | 39 +- .../utils/src/Utils/DateTimeImmutable.php | 187 ------ vendor/nette/utils/src/Utils/FileInfo.php | 5 +- vendor/nette/utils/src/Utils/FileSystem.php | 61 +- vendor/nette/utils/src/Utils/Finder.php | 132 ++--- vendor/nette/utils/src/Utils/Floats.php | 1 - vendor/nette/utils/src/Utils/Helpers.php | 16 +- vendor/nette/utils/src/Utils/Html.php | 326 +++++----- vendor/nette/utils/src/Utils/Image.php | 197 +++--- vendor/nette/utils/src/Utils/ImageColor.php | 9 +- vendor/nette/utils/src/Utils/ImageType.php | 4 +- vendor/nette/utils/src/Utils/Iterables.php | 38 +- vendor/nette/utils/src/Utils/Json.php | 15 +- .../nette/utils/src/Utils/ObjectHelpers.php | 12 +- vendor/nette/utils/src/Utils/Paginator.php | 57 +- vendor/nette/utils/src/Utils/Process.php | 560 ------------------ vendor/nette/utils/src/Utils/Reflection.php | 46 +- .../utils/src/Utils/ReflectionMethod.php | 7 +- vendor/nette/utils/src/Utils/Strings.php | 191 +++--- vendor/nette/utils/src/Utils/Type.php | 89 ++- vendor/nette/utils/src/Utils/Validators.php | 28 +- vendor/nette/utils/src/Utils/exceptions.php | 16 - .../symfony/deprecation-contracts/.gitignore | 3 + vendor/symfony/deprecation-contracts/LICENSE | 2 +- .../symfony/deprecation-contracts/README.md | 2 +- .../deprecation-contracts/composer.json | 4 +- vendor/symfony/polyfill-php80/PhpToken.php | 10 +- 85 files changed, 1398 insertions(+), 2198 deletions(-) delete mode 100644 vendor/nette/utils/src/Utils/DateTimeImmutable.php delete mode 100644 vendor/nette/utils/src/Utils/Process.php create mode 100644 vendor/symfony/deprecation-contracts/.gitignore diff --git a/changelog.txt b/changelog.txt index 1700450..908e43b 100644 --- a/changelog.txt +++ b/changelog.txt @@ -1,5 +1,47 @@ == Changelog == += 1.2.3 = + +_Release date: 2026-11-04_ + +**Highlights** + +* Tested up to WordPress 7.2 and PHP 8.6; real minimums re-verified (WordPress 4.2, PHP 8.0) +* Admin menu icon replaced with an inline SVG (WordPress core is moving from the Dashicons font to SVG in 7.2 — Trac #65089 / PR #12270) +* PHPStan raised to level 10 — the maximum — with no baseline + +**Security** + +* No security findings in this release; `composer audit` clean for both production and dev dependency sets + +**Changed** + +* Admin menu icon switched from `dashicons-media-document` to a base64 SVG data URI. Core has special-cased `data:image/svg+xml;base64,` menu icons since WordPress 4.2, so the icon renders identically on every supported version and does not depend on the new WordPress-7.2-only `wp_get_icon()` API +* PHPStan static analysis raised from level 9 to level 10 (the maximum, no baseline): the `robotstxt_docmd_input_string()` / `robotstxt_docmd_input_int()` helpers now document their `$input` parameter as `array` (superglobals and `get_option()` returns carry no string-key guarantee), `WP_Query::$posts` is type-narrowed with `is_array()` (wordpress-stubs 7.1 types it as nullable), `global $wpdb` is type-narrowed with an `instanceof wpdb` guard, and post-type label output is narrowed to string +* The transient-cleanup queries (debug "Clear All Plugin Caches" and `uninstall.php` prefix deletes) now build LIKE patterns with the `esc_sql( $wpdb->esc_like( ... ) )` chain documented in `wpdb::esc_like()`, instead of `$wpdb->prepare()`. Reason: wordpress-stubs types `wpdb::prepare()`'s query parameter as `literal-string`, which table-name interpolation can never satisfy; the escaping chain offers equivalent safety for bulk prefix deletes. Deliberate, documented exception to the AGENTS-security "prepare() for all custom SQL" checklist item +* `robotstxt_docmd_get_all_mappings()` iterates a narrowed copy of `WP_Query::$posts` (nullable in the WordPress 7.1 stubs) + +**Dependencies** + +* league/commonmark 2.10.0 → 2.10.7 (production; no known CVEs). phpstan 2.2.9 → 2.3.5, szepeviktor/phpstan-wordpress 2.0.3 → 2.0.4, php-stubs/wordpress-stubs 6.9.4 → 7.1.2, phpunit 9.6.36 → 9.6.38 (dev only) +* Composer platform pin added at `8.0.99` (the declared PHP floor). The unpinned update had promoted nette/schema 1.4.0 (PHP 8.1-only syntax on the Markdown-conversion autoload path) and nette/utils 4.1.6 (PHP 8.2+) into the production vendor tree — a fatal error on PHP 8.0/8.1 sites caught by the 1.2.3 pre-deploy audit (docs/audit-pre-deploy-1.2.3.md). With the pin the resolver ships nette/schema 1.2.5, nette/utils 4.0.11, and symfony/deprecation-contracts 3.0.2 — every shipped package supports PHP 8.0; conversion verified empirically +* `bin/preflight.sh` section 6 now builds the production vendor in a throwaway /tmp copy and fails unless the composer platform pin matches the header's `Requires PHP` and the production vendor installs under that pin + +**Compatibility** + +* WordPress: 4.2 - 7.2 (floor re-verified with WP-Compat; smoke-tested on WordPress 7.2-beta4 / PHP 8.6) +* PHP: 8.0 - 8.6 (floor re-verified with PHPCompatibility 5.6-8.6 full-range scan; binding 8.0 constraints: union return types, `str_starts_with()` / `str_contains()`, `mixed` parameter type) +* MariaDB: 11.4 or newer (no DB changes in this release) + +**Tests** + +* PHP Coding Standards: PHPCS 3.13.6 with WordPress-Core, WordPress-Docs, WordPress-Extra (WPCS 3.4.1) — 0 errors +* PHPStan: level 10 (maximum), 0 errors, no baseline (phpstan 2.3.5 + phpstan-wordpress 2.0.4, stubs 7.1.2) +* PHPCompatibility: 10.0.0-alpha2 — PHP 8.0-8.6 validated (full-range scan 5.6-8.6) +* WP-Compat: 1.5.0 — WordPress 4.2 floor validated (`wp_delete_file()` is the oldest API used) +* PHPUnit: 23 tests pass (17 plugin header tests + 6 Manager-detection tests) +* Manual testing: WordPress 7.2-beta4 single site, PHP 8.6.0RC3 — plugin active, mappings list, debug helpers, and admin menu verified; debug.log clean + = 1.2.2 = _Release date: 2026-08-24_ diff --git a/readme.txt b/readme.txt index ac59063..8ed2854 100644 --- a/readme.txt +++ b/readme.txt @@ -2,9 +2,9 @@ Contributors: robotstxt, javiercasares Tags: github, documentation, markdown, sync, automation Requires at least: 4.2 -Tested up to: 7.1 +Tested up to: 7.2 Requires PHP: 8.0 -Stable tag: 1.2.2 +Stable tag: 1.2.3 License: GPLv3 or later License URI: https://www.gnu.org/licenses/gpl-3.0.html @@ -182,13 +182,35 @@ Then go to Documentation → Settings, and you'll see a "Debug Tools" section at == Compatibility == -* WordPress: 4.2 - 7.1 -* PHP: 8.0 - 8.5 +* WordPress: 4.2 - 7.2 +* PHP: 8.0 - 8.6 == Changelog == For the complete changelog, see [changelog.txt](https://www.robotstxt.software/plugins/robotstxt-documentation-markdown/). += 1.2.3 - 2026-11-04 = + +**Changed** + +* Admin menu icon switched from the `dashicons-media-document` font glyph to an inline SVG (base64 data URI) — crisp at any resolution and aligned with the WordPress move from Dashicons to SVG icons (WordPress 7.2 / Trac #65089). Renders identically on every supported WordPress version (4.2 – 7.2); no dependency on the new WP 7.2-only `wp_get_icon()` API +* PHPStan static analysis raised from level 9 to level 10 (the maximum, no baseline): `$_POST`/`$_GET` input helpers now documented as accepting `array`, `WP_Query::$posts` and `global $wpdb` type-narrowed, post-type labels narrowed to string +* The two transient-cleanup queries (debug "Clear All Plugin Caches" and uninstall) now escape LIKE patterns with the `esc_sql( $wpdb->esc_like( ... ) )` chain documented in `wpdb::esc_like()`, instead of `$wpdb->prepare()` — equivalent safety for bulk prefix deletes +* `composer update`: league/commonmark 2.10.0 → 2.10.7 (production, no known CVEs); phpstan 2.3.5, wordpress-stubs 7.1.2 (dev). Composer platform pin added at the PHP 8.0 floor so the shipped vendor tree can never require a newer PHP than declared (`nette/schema` 1.4.0 / `nette/utils` 4.1.6 needed PHP 8.1/8.2; the pin ships 1.2.5 / 4.0.11 instead). `composer audit` clean + +**Compatibility** + +* WordPress: 4.2 - 7.2 (floor re-verified with WP-Compat; smoke-tested on WordPress 7.2-beta4) +* PHP: 8.0 - 8.6 (floor re-verified with PHPCompatibility 5.6-8.6 full-range scan) + +**Tests** + +* PHP Coding Standards: PHPCS with WordPress-Core, WordPress-Docs, WordPress-Extra — 0 errors +* PHPStan: level 10 (maximum), 0 errors, no baseline +* PHPCompatibility: PHP 8.0-8.6 validated (full-range scan 5.6-8.6) +* WP-Compat: WordPress 4.2 floor validated +* PHPUnit: 23 tests pass (17 plugin header tests + 6 Manager-detection tests) + = 1.2.2 - 2026-08-24 = **Changed** @@ -227,35 +249,15 @@ For the complete changelog, see [changelog.txt](https://www.robotstxt.software/p * Spanish (es_ES) and Catalan (ca): 10 missing strings from 1.2.0 added, plus the new Manager notice -= 1.2.0 - 2026-08-07 = += Previous versions = -**Added** - -* **Title from H1:** the synced post title is now taken from the first `# H1` in the Markdown (inline formatting stripped), with the H1 removed from the body to avoid a duplicate heading. Falls back to the filename-derived title when no H1 is present -* **Internal link translation:** repo-relative Markdown links (e.g. `./api.md`, `../README.md`) are rewritten to the permalink of the matching mapped WordPress content. External, `mailto:`, and anchor links are left untouched; links with no matching mapping keep their original URL -* **Repository image sideloading:** images referenced in the Markdown are downloaded from the repository, added to the Media Library, and their references replaced with the attachment URL. Already-imported images are reused on subsequent syncs (tracked per post); removed images are kept in the Media Library (non-destructive) - -**Security** - -* Patched CVE-2026-71478 (and advisory GHSA-2q4p-g7hv-5rgv) in league/commonmark — an unsafe-link filter bypass that could defeat `allow_unsafe_links: false`. Updated league/commonmark 2.8.2 → 2.9.0 -* GitHub token encryption now derives its AES-256 key with HKDF-SHA256 from `wp_salt('auth')` instead of using the salt directly; existing tokens are migrated transparently to the new `v2:` format on first decrypt (covers the cron path too) -* Discover Files "Refresh from GitHub" action is now nonce-protected — previously a crafted link could force an unrequested GitHub API call (CSRF) -* GitHub API request paths are now `rawurlencode()`d (defensive hardening) -* Sideloaded images are validated by extension (jpg, jpeg, png, gif, webp) and size (< 10 MB) before storage; SVG is intentionally excluded - -**Fixed** - -* "Using cached data / fetching fresh data" indicator on Discover Files now reflects reality — it always showed "cached" because the cache was tested after being populated -* `target_post_type` is now validated against registered public post types on save, falling back to `page` (prevents saving an unregistered or internal type) -* Debug action dispatch refactored into a single `switch`, each case retaining its `check_admin_referer()` check, to reduce the chance of a missing nonce check - -**Changed** - -* Inline `onclick` confirm on Delete replaced with a `data-confirm` attribute + delegated handler (CSP-friendlier, less fragile) -* Add Mapping "existing content" dropdown now queries only public post types (excludes attachments and the internal mapping CPT) with `no_found_rows` for better performance on large sites +If you want to see the full changelog, visit the [changelog.txt](https://www.robotstxt.software/plugins/robotstxt-documentation-markdown/) file. == Upgrade Notice == += 1.2.3 = +Tested up to WordPress 7.2 and PHP 8.6. New SVG admin menu icon; no settings or data changes are needed. + = 1.2.2 = Manager (by ROBOTSTXT) detection updated: now uses the ROBOTSTXT_MANAGER_NOTICED presence constant (Manager 1.6.2+) with a fallback for older Manager versions. diff --git a/robotstxt-documentation-markdown-functions.php b/robotstxt-documentation-markdown-functions.php index 1fd5c21..a85d877 100644 --- a/robotstxt-documentation-markdown-functions.php +++ b/robotstxt-documentation-markdown-functions.php @@ -230,10 +230,12 @@ function robotstxt_docmd_get_status_badge( string $status ): string { * Provides PHPStan level 9 compliant type-narrowing for superglobal access. * * @since 1.0.1 + * @since 1.2.3 Parameter documented as array — superglobals and + * get_option() returns are not guaranteed to have string keys. * - * @param array $input The superglobal array ($_POST, $_GET, etc.). - * @param string $key The key to look for. - * @param string $fallback Default value if key not found or not a string. + * @param array $input The superglobal array ($_POST, $_GET, etc.). + * @param string $key The key to look for. + * @param string $fallback Default value if key not found or not a string. * @return string */ function robotstxt_docmd_input_string( array $input, string $key, string $fallback = '' ): string { @@ -249,10 +251,12 @@ function robotstxt_docmd_input_string( array $input, string $key, string $fallba * Provides PHPStan level 9 compliant type-narrowing for superglobal access. * * @since 1.0.1 + * @since 1.2.3 Parameter documented as array — superglobals and + * get_option() returns are not guaranteed to have string keys. * - * @param array $input The superglobal array ($_POST, $_GET, etc.). - * @param string $key The key to look for. - * @param int $fallback Default value if key not found or not numeric. + * @param array $input The superglobal array ($_POST, $_GET, etc.). + * @param string $key The key to look for. + * @param int $fallback Default value if key not found or not numeric. * @return int */ function robotstxt_docmd_input_int( array $input, string $key, int $fallback = 0 ): int { diff --git a/robotstxt-documentation-markdown-map.php b/robotstxt-documentation-markdown-map.php index e9514c9..c602685 100644 --- a/robotstxt-documentation-markdown-map.php +++ b/robotstxt-documentation-markdown-map.php @@ -27,9 +27,10 @@ function robotstxt_docmd_get_all_mappings(): array { ); $query = new WP_Query( $args ); + $posts = is_array( $query->posts ) ? $query->posts : array(); $mappings = array(); - foreach ( $query->posts as $post ) { + foreach ( $posts as $post ) { if ( ! ( $post instanceof WP_Post ) ) { continue; } diff --git a/robotstxt-documentation-markdown.php b/robotstxt-documentation-markdown.php index a6430a2..5786dee 100644 --- a/robotstxt-documentation-markdown.php +++ b/robotstxt-documentation-markdown.php @@ -3,7 +3,7 @@ * Plugin Name: Documentation Markdown (by ROBOTSTXT) * Plugin URI: https://www.robotstxt.software/plugins/robotstxt-documentation-markdown/ * Description: Synchronizes Markdown documentation from GitHub repositories to WordPress pages and posts automatically. - * Version: 1.2.2 + * Version: 1.2.3 * Requires at least: 4.2 * Requires PHP: 8.0 * Security: robotstxt@robotstxt.es @@ -25,7 +25,7 @@ if ( ! defined( 'ABSPATH' ) ) { } // Define plugin constants. -define( 'ROBOTSTXT_DOCMD_VERSION', '1.2.2' ); +define( 'ROBOTSTXT_DOCMD_VERSION', '1.2.3' ); define( 'ROBOTSTXT_DOCMD_PLUGIN_FILE', __FILE__ ); define( 'ROBOTSTXT_DOCMD_PLUGIN_DIR', plugin_dir_path( __FILE__ ) ); define( 'ROBOTSTXT_DOCMD_PLUGIN_URL', plugin_dir_url( __FILE__ ) ); @@ -146,6 +146,13 @@ function robotstxt_docmd_register_post_types() { * @return void */ function robotstxt_docmd_register_admin_menu() { + // Base64 SVG data URI (document icon). Supported by core admin menus from + // WP 4.2 through 7.2+ (rendered as a 20px background image); aligns the icon + // with core's move from the Dashicons font to SVG (see WP ticket #65089), + // without requiring the WP 7.2-only wp_get_icon() API. + // phpcs:ignore Generic.Files.LineLength.TooLong -- 264-char base64 icon string cannot be wrapped. + $icon = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyMCAyMCI+PHBhdGggZmlsbD0iI2MzYzRjNyIgZmlsbC1ydWxlPSJldmVub2RkIiBkPSJNNSAxaDdsNCA0djE0SDVWMXptNyAxLjdWNmgzLjNMMTIgMi43ek03IDloNnYxSDdWOXptMCAzaDcuNXYxSDd2LTF6bTAgM2g3LjV2MUg3di0xeiIvPjwvc3ZnPg=='; + // Main menu. add_menu_page( __( 'Documentation', 'robotstxt-documentation-markdown' ), @@ -153,7 +160,7 @@ function robotstxt_docmd_register_admin_menu() { 'edit_pages', 'robotstxt-docmd-mappings', 'robotstxt_docmd_render_mappings_page', - 'dashicons-media-document', + $icon, 30 ); @@ -735,11 +742,12 @@ function robotstxt_docmd_render_add_mapping_page() { true ), 'objects' ); foreach ( $post_types as $post_type ) { + $label = $post_type->labels->singular_name; printf( '', esc_attr( $post_type->name ), selected( $data['target_post_type'], $post_type->name, false ), - esc_html( $post_type->labels->singular_name ) + esc_html( is_string( $label ) ? $label : $post_type->name ) ); } ?> @@ -1579,6 +1587,11 @@ function robotstxt_docmd_debug_clear_cache() { global $wpdb; + // Type-narrow the global (PHPStan level 10: global $wpdb is mixed). + if ( ! $wpdb instanceof wpdb ) { + return; + } + $result = array( 'type' => 'error', 'message' => '', @@ -1586,16 +1599,19 @@ function robotstxt_docmd_debug_clear_cache() { ); // Delete all plugin transients. - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Direct query acceptable for cache clearing operation. + // Escaping uses the esc_sql() + esc_like() chain documented in wpdb::esc_like(): + // wpdb::prepare() cannot be used here because table-name interpolation makes + // the query string non-literal (wordpress-stubs types $query as literal-string). + $transient_like = esc_sql( $wpdb->esc_like( '_transient_robotstxt_docmd_' ) ) . '%'; + $timeout_like = esc_sql( $wpdb->esc_like( '_transient_timeout_robotstxt_docmd_' ) ) . '%'; + + // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Bulk cache-clearing delete; values escaped above via esc_sql() + esc_like(). $deleted = $wpdb->query( - $wpdb->prepare( - "DELETE FROM {$wpdb->options} - WHERE option_name LIKE %s - OR option_name LIKE %s", - $wpdb->esc_like( '_transient_robotstxt_docmd_' ) . '%', - $wpdb->esc_like( '_transient_timeout_robotstxt_docmd_' ) . '%' - ) + "DELETE FROM {$wpdb->options} + WHERE option_name LIKE '{$transient_like}' + OR option_name LIKE '{$timeout_like}'" ); + // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared if ( false !== $deleted ) { $result['type'] = 'success'; diff --git a/uninstall.php b/uninstall.php index 3810527..83941b2 100644 --- a/uninstall.php +++ b/uninstall.php @@ -90,27 +90,29 @@ function robotstxt_docmd_uninstall(): void { function robotstxt_docmd_delete_transients_by_prefix( string $prefix ): void { global $wpdb; - // Sanitize prefix for LIKE query. - $transient_prefix = $wpdb->esc_like( '_transient_' . $prefix ) . '%'; - $transient_timeout_prefix = $wpdb->esc_like( '_transient_timeout_' . $prefix ) . '%'; + // Type-narrow the global (PHPStan level 10: global $wpdb is mixed). + if ( ! $wpdb instanceof wpdb ) { + return; + } - // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Required for bulk pattern-based deletion; no WordPress API available for this operation. + // Sanitize prefix for the LIKE pattern. Escaping uses the esc_sql() + + // esc_like() chain documented in wpdb::esc_like(): wpdb::prepare() cannot + // be used here because table-name interpolation makes the query string + // non-literal (wordpress-stubs types $query as literal-string). + $transient_prefix = esc_sql( $wpdb->esc_like( '_transient_' . $prefix ) ) . '%'; + $transient_timeout_prefix = esc_sql( $wpdb->esc_like( '_transient_timeout_' . $prefix ) ) . '%'; + + // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Required for bulk pattern-based deletion; no WordPress API available. Values escaped above via esc_sql() + esc_like(). // Delete transient values. $wpdb->query( - $wpdb->prepare( - "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", - $transient_prefix - ) + "DELETE FROM {$wpdb->options} WHERE option_name LIKE '{$transient_prefix}'" ); // Delete transient timeouts. $wpdb->query( - $wpdb->prepare( - "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", - $transient_timeout_prefix - ) + "DELETE FROM {$wpdb->options} WHERE option_name LIKE '{$transient_timeout_prefix}'" ); - // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching + // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared } // Run uninstall. diff --git a/vendor/autoload.php b/vendor/autoload.php index ff6fe0d..cae08aa 100644 --- a/vendor/autoload.php +++ b/vendor/autoload.php @@ -19,4 +19,4 @@ if (PHP_VERSION_ID < 50600) { require_once __DIR__ . '/composer/autoload_real.php'; -return ComposerAutoloaderInitc097ca862608a882f291ae6b935e271c::getLoader(); +return ComposerAutoloaderInit58fc5ab3eee1b67eedbe2aa42d9005e6::getLoader(); diff --git a/vendor/composer/autoload_classmap.php b/vendor/composer/autoload_classmap.php index 385b431..1f54411 100644 --- a/vendor/composer/autoload_classmap.php +++ b/vendor/composer/autoload_classmap.php @@ -366,7 +366,6 @@ return array( 'Nette\\Utils\\AssertionException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php', 'Nette\\Utils\\Callback' => $vendorDir . '/nette/utils/src/Utils/Callback.php', 'Nette\\Utils\\DateTime' => $vendorDir . '/nette/utils/src/Utils/DateTime.php', - 'Nette\\Utils\\DateTimeImmutable' => $vendorDir . '/nette/utils/src/Utils/DateTimeImmutable.php', 'Nette\\Utils\\FileInfo' => $vendorDir . '/nette/utils/src/Utils/FileInfo.php', 'Nette\\Utils\\FileSystem' => $vendorDir . '/nette/utils/src/Utils/FileSystem.php', 'Nette\\Utils\\Finder' => $vendorDir . '/nette/utils/src/Utils/Finder.php', @@ -383,9 +382,6 @@ return array( 'Nette\\Utils\\JsonException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php', 'Nette\\Utils\\ObjectHelpers' => $vendorDir . '/nette/utils/src/Utils/ObjectHelpers.php', 'Nette\\Utils\\Paginator' => $vendorDir . '/nette/utils/src/Utils/Paginator.php', - 'Nette\\Utils\\Process' => $vendorDir . '/nette/utils/src/Utils/Process.php', - 'Nette\\Utils\\ProcessFailedException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php', - 'Nette\\Utils\\ProcessTimeoutException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php', 'Nette\\Utils\\Random' => $vendorDir . '/nette/utils/src/Utils/Random.php', 'Nette\\Utils\\Reflection' => $vendorDir . '/nette/utils/src/Utils/Reflection.php', 'Nette\\Utils\\ReflectionMethod' => $vendorDir . '/nette/utils/src/Utils/ReflectionMethod.php', diff --git a/vendor/composer/autoload_psr4.php b/vendor/composer/autoload_psr4.php index ae8aaf1..eabb789 100644 --- a/vendor/composer/autoload_psr4.php +++ b/vendor/composer/autoload_psr4.php @@ -8,7 +8,7 @@ $baseDir = dirname($vendorDir); return array( 'Symfony\\Polyfill\\Php80\\' => array($vendorDir . '/symfony/polyfill-php80'), 'Psr\\EventDispatcher\\' => array($vendorDir . '/psr/event-dispatcher/src'), - 'Nette\\' => array($vendorDir . '/nette/schema/src', $vendorDir . '/nette/utils/src'), + 'Nette\\' => array($vendorDir . '/nette/utils/src'), 'League\\Config\\' => array($vendorDir . '/league/config/src'), 'League\\CommonMark\\' => array($vendorDir . '/league/commonmark/src'), 'Dflydev\\DotAccessData\\' => array($vendorDir . '/dflydev/dot-access-data/src'), diff --git a/vendor/composer/autoload_real.php b/vendor/composer/autoload_real.php index cad8f69..9304804 100644 --- a/vendor/composer/autoload_real.php +++ b/vendor/composer/autoload_real.php @@ -2,7 +2,7 @@ // autoload_real.php @generated by Composer -class ComposerAutoloaderInitc097ca862608a882f291ae6b935e271c +class ComposerAutoloaderInit58fc5ab3eee1b67eedbe2aa42d9005e6 { private static $loader; @@ -24,16 +24,16 @@ class ComposerAutoloaderInitc097ca862608a882f291ae6b935e271c require __DIR__ . '/platform_check.php'; - spl_autoload_register(array('ComposerAutoloaderInitc097ca862608a882f291ae6b935e271c', 'loadClassLoader'), true, true); + spl_autoload_register(array('ComposerAutoloaderInit58fc5ab3eee1b67eedbe2aa42d9005e6', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__)); - spl_autoload_unregister(array('ComposerAutoloaderInitc097ca862608a882f291ae6b935e271c', 'loadClassLoader')); + spl_autoload_unregister(array('ComposerAutoloaderInit58fc5ab3eee1b67eedbe2aa42d9005e6', 'loadClassLoader')); require __DIR__ . '/autoload_static.php'; - call_user_func(\Composer\Autoload\ComposerStaticInitc097ca862608a882f291ae6b935e271c::getInitializer($loader)); + call_user_func(\Composer\Autoload\ComposerStaticInit58fc5ab3eee1b67eedbe2aa42d9005e6::getInitializer($loader)); $loader->register(true); - $filesToLoad = \Composer\Autoload\ComposerStaticInitc097ca862608a882f291ae6b935e271c::$files; + $filesToLoad = \Composer\Autoload\ComposerStaticInit58fc5ab3eee1b67eedbe2aa42d9005e6::$files; $requireFile = \Closure::bind(static function ($fileIdentifier, $file) { if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; diff --git a/vendor/composer/autoload_static.php b/vendor/composer/autoload_static.php index bdcd0e5..0824fee 100644 --- a/vendor/composer/autoload_static.php +++ b/vendor/composer/autoload_static.php @@ -4,7 +4,7 @@ namespace Composer\Autoload; -class ComposerStaticInitc097ca862608a882f291ae6b935e271c +class ComposerStaticInit58fc5ab3eee1b67eedbe2aa42d9005e6 { public static $files = array ( '6e3fae29631ef280660b3cdad06f25a8' => __DIR__ . '/..' . '/symfony/deprecation-contracts/function.php', @@ -46,8 +46,7 @@ class ComposerStaticInitc097ca862608a882f291ae6b935e271c ), 'Nette\\' => array ( - 0 => __DIR__ . '/..' . '/nette/schema/src', - 1 => __DIR__ . '/..' . '/nette/utils/src', + 0 => __DIR__ . '/..' . '/nette/utils/src', ), 'League\\Config\\' => array ( @@ -424,7 +423,6 @@ class ComposerStaticInitc097ca862608a882f291ae6b935e271c 'Nette\\Utils\\AssertionException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', 'Nette\\Utils\\Callback' => __DIR__ . '/..' . '/nette/utils/src/Utils/Callback.php', 'Nette\\Utils\\DateTime' => __DIR__ . '/..' . '/nette/utils/src/Utils/DateTime.php', - 'Nette\\Utils\\DateTimeImmutable' => __DIR__ . '/..' . '/nette/utils/src/Utils/DateTimeImmutable.php', 'Nette\\Utils\\FileInfo' => __DIR__ . '/..' . '/nette/utils/src/Utils/FileInfo.php', 'Nette\\Utils\\FileSystem' => __DIR__ . '/..' . '/nette/utils/src/Utils/FileSystem.php', 'Nette\\Utils\\Finder' => __DIR__ . '/..' . '/nette/utils/src/Utils/Finder.php', @@ -441,9 +439,6 @@ class ComposerStaticInitc097ca862608a882f291ae6b935e271c 'Nette\\Utils\\JsonException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', 'Nette\\Utils\\ObjectHelpers' => __DIR__ . '/..' . '/nette/utils/src/Utils/ObjectHelpers.php', 'Nette\\Utils\\Paginator' => __DIR__ . '/..' . '/nette/utils/src/Utils/Paginator.php', - 'Nette\\Utils\\Process' => __DIR__ . '/..' . '/nette/utils/src/Utils/Process.php', - 'Nette\\Utils\\ProcessFailedException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', - 'Nette\\Utils\\ProcessTimeoutException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', 'Nette\\Utils\\Random' => __DIR__ . '/..' . '/nette/utils/src/Utils/Random.php', 'Nette\\Utils\\Reflection' => __DIR__ . '/..' . '/nette/utils/src/Utils/Reflection.php', 'Nette\\Utils\\ReflectionMethod' => __DIR__ . '/..' . '/nette/utils/src/Utils/ReflectionMethod.php', @@ -466,9 +461,9 @@ class ComposerStaticInitc097ca862608a882f291ae6b935e271c public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { - $loader->prefixLengthsPsr4 = ComposerStaticInitc097ca862608a882f291ae6b935e271c::$prefixLengthsPsr4; - $loader->prefixDirsPsr4 = ComposerStaticInitc097ca862608a882f291ae6b935e271c::$prefixDirsPsr4; - $loader->classMap = ComposerStaticInitc097ca862608a882f291ae6b935e271c::$classMap; + $loader->prefixLengthsPsr4 = ComposerStaticInit58fc5ab3eee1b67eedbe2aa42d9005e6::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInit58fc5ab3eee1b67eedbe2aa42d9005e6::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInit58fc5ab3eee1b67eedbe2aa42d9005e6::$classMap; }, null, ClassLoader::class); } diff --git a/vendor/composer/installed.json b/vendor/composer/installed.json index 350ecaf..717a352 100644 --- a/vendor/composer/installed.json +++ b/vendor/composer/installed.json @@ -80,17 +80,17 @@ }, { "name": "league/commonmark", - "version": "2.10.0", - "version_normalized": "2.10.0.0", + "version": "2.10.7", + "version_normalized": "2.10.7.0", "source": { "type": "git", "url": "https://github.com/thephpleague/commonmark.git", - "reference": "d2d1aa8b35e072966c89bc0c66cf926e56767dc4" + "reference": "8eb53e906fd60c67038d22f1f1cab420ed58b8be" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/thephpleague/commonmark/zipball/d2d1aa8b35e072966c89bc0c66cf926e56767dc4", - "reference": "d2d1aa8b35e072966c89bc0c66cf926e56767dc4", + "url": "https://api.github.com/repos/thephpleague/commonmark/zipball/8eb53e906fd60c67038d22f1f1cab420ed58b8be", + "reference": "8eb53e906fd60c67038d22f1f1cab420ed58b8be", "shasum": "" }, "require": { @@ -124,7 +124,7 @@ "suggest": { "symfony/yaml": "v2.3+ required if using the Front Matter extension" }, - "time": "2026-08-11T16:06:25+00:00", + "time": "2026-10-31T13:35:37+00:00", "type": "library", "extra": { "branch-alias": { @@ -275,42 +275,37 @@ }, { "name": "nette/schema", - "version": "v1.3.6", - "version_normalized": "1.3.6.0", + "version": "v1.2.5", + "version_normalized": "1.2.5.0", "source": { "type": "git", "url": "https://github.com/nette/schema.git", - "reference": "c54350438cd6914616f790a49cb424605f421562" + "reference": "0462f0166e823aad657c9224d0f849ecac1ba10a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/nette/schema/zipball/c54350438cd6914616f790a49cb424605f421562", - "reference": "c54350438cd6914616f790a49cb424605f421562", + "url": "https://api.github.com/repos/nette/schema/zipball/0462f0166e823aad657c9224d0f849ecac1ba10a", + "reference": "0462f0166e823aad657c9224d0f849ecac1ba10a", "shasum": "" }, "require": { - "nette/utils": "^4.0", - "php": "8.1 - 8.5" + "nette/utils": "^2.5.7 || ^3.1.5 || ^4.0", + "php": "7.1 - 8.3" }, "require-dev": { - "nette/phpstan-rules": "^1.0", - "nette/tester": "^2.6", - "phpstan/extension-installer": "^1.4@stable", - "phpstan/phpstan": "^2.1.39@stable", - "tracy/tracy": "^2.8" + "nette/tester": "^2.3 || ^2.4", + "phpstan/phpstan-nette": "^1.0", + "tracy/tracy": "^2.7" }, - "time": "2026-08-16T21:58:41+00:00", + "time": "2023-10-05T20:37:59+00:00", "type": "library", "extra": { "branch-alias": { - "dev-master": "1.3-dev" + "dev-master": "1.2-dev" } }, "installation-source": "dist", "autoload": { - "psr-4": { - "Nette\\": "src" - }, "classmap": [ "src/" ] @@ -339,27 +334,27 @@ ], "support": { "issues": "https://github.com/nette/schema/issues", - "source": "https://github.com/nette/schema/tree/v1.3.6" + "source": "https://github.com/nette/schema/tree/v1.2.5" }, "install-path": "../nette/schema" }, { "name": "nette/utils", - "version": "v4.1.5", - "version_normalized": "4.1.5.0", + "version": "v4.0.11", + "version_normalized": "4.0.11.0", "source": { "type": "git", "url": "https://github.com/nette/utils.git", - "reference": "b043439dbdf954e6c28b5ea7e34b0100f83165e0" + "reference": "c9958d457077885860569245ffbf66f8131f36cb" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/nette/utils/zipball/b043439dbdf954e6c28b5ea7e34b0100f83165e0", - "reference": "b043439dbdf954e6c28b5ea7e34b0100f83165e0", + "url": "https://api.github.com/repos/nette/utils/zipball/c9958d457077885860569245ffbf66f8131f36cb", + "reference": "c9958d457077885860569245ffbf66f8131f36cb", "shasum": "" }, "require": { - "php": "8.2 - 8.5" + "php": "8.0 - 8.6" }, "conflict": { "nette/finder": "<3", @@ -367,25 +362,23 @@ }, "require-dev": { "jetbrains/phpstorm-attributes": "^1.2", - "nette/phpstan-rules": "^1.0", "nette/tester": "^2.5", - "phpstan/extension-installer": "^1.4@stable", - "phpstan/phpstan": "^2.1@stable", + "phpstan/phpstan-nette": "^2.0@stable", "tracy/tracy": "^2.9" }, "suggest": { "ext-gd": "to use Image", - "ext-iconv": "to use Strings::chr(), ord() and reverse()", + "ext-iconv": "to use Strings::webalize(), toAscii(), chr() and reverse()", "ext-intl": "to use Strings::webalize(), toAscii(), normalize() and compare()", "ext-json": "to use Nette\\Utils\\Json", "ext-mbstring": "to use Strings::lower() etc...", "ext-tokenizer": "to use Nette\\Utils\\Reflection::getUseStatements()" }, - "time": "2026-07-17T23:02:45+00:00", + "time": "2026-10-21T16:50:30+00:00", "type": "library", "extra": { "branch-alias": { - "dev-master": "4.1-dev" + "dev-master": "4.0-dev" } }, "installation-source": "dist", @@ -433,7 +426,7 @@ ], "support": { "issues": "https://github.com/nette/utils/issues", - "source": "https://github.com/nette/utils/tree/v4.1.5" + "source": "https://github.com/nette/utils/tree/v4.0.11" }, "install-path": "../nette/utils" }, @@ -492,23 +485,23 @@ }, { "name": "symfony/deprecation-contracts", - "version": "v3.7.1", - "version_normalized": "3.7.1.0", + "version": "v3.0.2", + "version_normalized": "3.0.2.0", "source": { "type": "git", "url": "https://github.com/symfony/deprecation-contracts.git", - "reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d" + "reference": "26954b3d62a6c5fd0ea8a2a00c0353a14978d05c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/f3202fa1b5097b0af062dc978b32ecf63404e31d", - "reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/26954b3d62a6c5fd0ea8a2a00c0353a14978d05c", + "reference": "26954b3d62a6c5fd0ea8a2a00c0353a14978d05c", "shasum": "" }, "require": { - "php": ">=8.1" + "php": ">=8.0.2" }, - "time": "2026-06-05T06:23:12+00:00", + "time": "2022-01-02T09:55:41+00:00", "type": "library", "extra": { "thanks": { @@ -516,7 +509,7 @@ "name": "symfony/contracts" }, "branch-alias": { - "dev-main": "3.7-dev" + "dev-main": "3.0-dev" } }, "installation-source": "dist", @@ -542,7 +535,7 @@ "description": "A generic function and convention to trigger deprecation notices", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/deprecation-contracts/tree/v3.7.1" + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.0.2" }, "funding": [ { @@ -553,10 +546,6 @@ "url": "https://github.com/fabpot", "type": "github" }, - { - "url": "https://github.com/nicolas-grekas", - "type": "github" - }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" @@ -566,23 +555,23 @@ }, { "name": "symfony/polyfill-php80", - "version": "v1.37.0", - "version_normalized": "1.37.0.0", + "version": "v1.43.0", + "version_normalized": "1.43.0.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php80.git", - "reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411" + "reference": "9c6a5d6b01ca51d486c813e9a9c0ed55f208bb74" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/dfb55726c3a76ea3b6459fcfda1ec2d80a682411", - "reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/9c6a5d6b01ca51d486c813e9a9c0ed55f208bb74", + "reference": "9c6a5d6b01ca51d486c813e9a9c0ed55f208bb74", "shasum": "" }, "require": { "php": ">=7.2" }, - "time": "2026-04-10T16:19:22+00:00", + "time": "2026-09-25T15:50:05+00:00", "type": "library", "extra": { "thanks": { @@ -629,7 +618,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-php80/tree/v1.37.0" + "source": "https://github.com/symfony/polyfill-php80/tree/v1.43.0" }, "funding": [ { diff --git a/vendor/composer/installed.php b/vendor/composer/installed.php index a249c41..ff2aec6 100644 --- a/vendor/composer/installed.php +++ b/vendor/composer/installed.php @@ -20,9 +20,9 @@ 'dev_requirement' => false, ), 'league/commonmark' => array( - 'pretty_version' => '2.10.0', - 'version' => '2.10.0.0', - 'reference' => 'd2d1aa8b35e072966c89bc0c66cf926e56767dc4', + 'pretty_version' => '2.10.7', + 'version' => '2.10.7.0', + 'reference' => '8eb53e906fd60c67038d22f1f1cab420ed58b8be', 'type' => 'library', 'install_path' => __DIR__ . '/../league/commonmark', 'aliases' => array(), @@ -38,18 +38,18 @@ 'dev_requirement' => false, ), 'nette/schema' => array( - 'pretty_version' => 'v1.3.6', - 'version' => '1.3.6.0', - 'reference' => 'c54350438cd6914616f790a49cb424605f421562', + 'pretty_version' => 'v1.2.5', + 'version' => '1.2.5.0', + 'reference' => '0462f0166e823aad657c9224d0f849ecac1ba10a', 'type' => 'library', 'install_path' => __DIR__ . '/../nette/schema', 'aliases' => array(), 'dev_requirement' => false, ), 'nette/utils' => array( - 'pretty_version' => 'v4.1.5', - 'version' => '4.1.5.0', - 'reference' => 'b043439dbdf954e6c28b5ea7e34b0100f83165e0', + 'pretty_version' => 'v4.0.11', + 'version' => '4.0.11.0', + 'reference' => 'c9958d457077885860569245ffbf66f8131f36cb', 'type' => 'library', 'install_path' => __DIR__ . '/../nette/utils', 'aliases' => array(), @@ -74,18 +74,18 @@ 'dev_requirement' => false, ), 'symfony/deprecation-contracts' => array( - 'pretty_version' => 'v3.7.1', - 'version' => '3.7.1.0', - 'reference' => 'f3202fa1b5097b0af062dc978b32ecf63404e31d', + 'pretty_version' => 'v3.0.2', + 'version' => '3.0.2.0', + 'reference' => '26954b3d62a6c5fd0ea8a2a00c0353a14978d05c', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/deprecation-contracts', 'aliases' => array(), 'dev_requirement' => false, ), 'symfony/polyfill-php80' => array( - 'pretty_version' => 'v1.37.0', - 'version' => '1.37.0.0', - 'reference' => 'dfb55726c3a76ea3b6459fcfda1ec2d80a682411', + 'pretty_version' => 'v1.43.0', + 'version' => '1.43.0.0', + 'reference' => '9c6a5d6b01ca51d486c813e9a9c0ed55f208bb74', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/polyfill-php80', 'aliases' => array(), diff --git a/vendor/composer/platform_check.php b/vendor/composer/platform_check.php index 14bf88d..d3df6d2 100644 --- a/vendor/composer/platform_check.php +++ b/vendor/composer/platform_check.php @@ -4,8 +4,8 @@ $issues = array(); -if (!(PHP_VERSION_ID >= 80200)) { - $issues[] = 'Your Composer dependencies require a PHP version ">= 8.2.0". You are running ' . PHP_VERSION . '.'; +if (!(PHP_VERSION_ID >= 80002)) { + $issues[] = 'Your Composer dependencies require a PHP version ">= 8.0.2". You are running ' . PHP_VERSION . '.'; } if ($issues) { diff --git a/vendor/league/commonmark/CHANGELOG.md b/vendor/league/commonmark/CHANGELOG.md index 815e8ec..cb4fce1 100644 --- a/vendor/league/commonmark/CHANGELOG.md +++ b/vendor/league/commonmark/CHANGELOG.md @@ -6,6 +6,56 @@ Updates should follow the [Keep a CHANGELOG](https://keepachangelog.com/) princi ## [Unreleased][unreleased] +## [2.10.7] - 2026-10-31 + +### Fixed +- Fixed `AutolinkExtension` keeping trailing punctuation inside very long URLs containing long runs of punctuation, and removed the excessive regex backtracking that caused it (#1170) + +## [2.10.6] - 2026-10-30 + +### Fixed +- Fixed `ExternalLinkExtension` not treating some links as external when browsers would navigate to an external host, such as `https:///example.com`, `http:example.com`, or `///example.com`; hosts are now determined the way browsers do (#1169) + +## [2.10.5] - 2026-10-30 + +### Fixed +- Fixed link reference definitions keeping a partially parsed title when the title on the following line is never closed or is followed by other text; the definition now has no title, as the spec requires (#1162) +- Fixed task list items being recognized when the `[ ]` or `[x]` marker is directly followed by other content (`- [x]done`); the GFM spec requires whitespace after the marker (#1164) +- Fixed the content indentation of a list item whose content is a single character after two to four spaces (`- a`): it was computed as if one space followed the marker, so the next line could be read as part of the item, nesting a following item inside it (#1163) +- Fixed a table inside a block quote or list item absorbing the lines that follow it as table rows when those lines are lazy continuation lines (not prefixed with `>` or indented); they now end the container as in GitHub's `cmark-gfm` (#1165) +- Fixed link reference definitions accepting an unescaped `(` inside a parenthesized title (#1168) + +## [2.10.4] - 2026-10-17 + +### Fixed +- Fixed `HeadingPermalinkExtension` overwriting an `id` set on a heading by the `AttributesExtension` when `heading_permalink/apply_id_to_heading` is enabled; the existing `id` is now used (with the configured prefix) for both the heading and its permalink (#1159, #1160) +- Fixed Symfony `DebugClassLoader` deprecation notice about `ArrayCollection::offsetGet()` by adding an explicit `@return` annotation (#1158) + +## [2.10.3] - 2026-09-21 + +### Fixed +- Fixed footnote links and backlinks pointing at the wrong anchor when `footnote/footnote_id_prefix` or `footnote/ref_id_prefix` contains an uppercase character; the configured prefix is now emitted verbatim in the `href` as it already was in the matching `id` (#524) +- Fixed inline raw HTML tags being escaped when the tag name or an attribute name contains an uppercase letter, such as `` or `` (#1096) + +## [2.10.2] - 2026-09-21 + +This is a **security release** to address a denial of service vulnerability in the `Table` extension and a raw HTML filtering bypass in the `DisallowedRawHtml` extension. + +### Changed +- Improved performance of parsing table delimiter rows and splitting table rows into cells by scanning bytes directly instead of stepping a `Cursor` (roughly 4x faster for delimiter rows and 6x for cell splitting, and more on multibyte rows) + +### Fixed +- Fixed `DisallowedRawHtmlRenderer` not blocking raw HTML that ends with a disallowed tag name, such as a line containing only ` `2.0`), the previous one ## 👷‍♀️ Contributing -To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure with us. +To report a security vulnerability, please see our [security policy](.github/SECURITY.md). If you encounter a bug in the spec, please report it to the [CommonMark] project. Any resulting fix will eventually be implemented in this project as well. diff --git a/vendor/league/commonmark/src/Extension/Autolink/UrlAutolinkParser.php b/vendor/league/commonmark/src/Extension/Autolink/UrlAutolinkParser.php index 97b5bd1..886d840 100644 --- a/vendor/league/commonmark/src/Extension/Autolink/UrlAutolinkParser.php +++ b/vendor/league/commonmark/src/Extension/Autolink/UrlAutolinkParser.php @@ -107,13 +107,8 @@ final class UrlAutolinkParser implements InlineParserInterface return false; } - $url = $matches[0]; - - // Does the URL end with punctuation that should be stripped? - if (\preg_match('/(.+?)([?!.,:*_~]+)$/', $url, $matches)) { - // Add the punctuation later - $url = $matches[1]; - } + // Strip trailing punctuation; it's left on the cursor to be parsed as text + $url = \rtrim($matches[0], '?!.,:*_~'); // Does the URL end with something that looks like an entity reference? if (\preg_match('/(.+)(&[A-Za-z0-9]+;)$/', $url, $matches)) { diff --git a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListBlockStartParser.php b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListBlockStartParser.php index a55f6f9..28977b2 100644 --- a/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListBlockStartParser.php +++ b/vendor/league/commonmark/src/Extension/CommonMark/Parser/Block/ListBlockStartParser.php @@ -123,7 +123,7 @@ final class ListBlockStartParser implements BlockStartParserInterface, Configura } } - $blankItem = $cursor->peek() === null; + $blankItem = $cursor->isAtEnd(); $spacesAfterMarker = $cursor->getColumn() - $spacesStartCol; if ($spacesAfterMarker >= 5 || $spacesAfterMarker < 1 || $blankItem) { diff --git a/vendor/league/commonmark/src/Extension/DisallowedRawHtml/DisallowedRawHtmlRenderer.php b/vendor/league/commonmark/src/Extension/DisallowedRawHtml/DisallowedRawHtmlRenderer.php index 2bcb89a..2b852e9 100644 --- a/vendor/league/commonmark/src/Extension/DisallowedRawHtml/DisallowedRawHtmlRenderer.php +++ b/vendor/league/commonmark/src/Extension/DisallowedRawHtml/DisallowedRawHtmlRenderer.php @@ -45,9 +45,11 @@ final class DisallowedRawHtmlRenderer implements NodeRendererInterface, Configur return $rendered; } - $regex = \sprintf('/<(\/?(?:%s)[\s\/>])/i', \implode('|', \array_map('preg_quote', $tags))); + // The tag name may also end the rendered HTML: the block parser accepts a bare + // `]|$))/i', \implode('|', \array_map('preg_quote', $tags))); - // Match these types of tags: <title /> + // Match these types of tags: <title> <title/> <title /> <title return \preg_replace($regex, '<$1', $rendered); } diff --git a/vendor/league/commonmark/src/Extension/ExternalLink/ExternalLinkProcessor.php b/vendor/league/commonmark/src/Extension/ExternalLink/ExternalLinkProcessor.php index 4a0aa89..6d98ad9 100644 --- a/vendor/league/commonmark/src/Extension/ExternalLink/ExternalLinkProcessor.php +++ b/vendor/league/commonmark/src/Extension/ExternalLink/ExternalLinkProcessor.php @@ -43,9 +43,9 @@ final class ExternalLinkProcessor continue; } - $host = \parse_url($link->getUrl(), PHP_URL_HOST); - if (! \is_string($host)) { - // Something is terribly wrong with this URL + $host = self::getHost($link->getUrl()); + if ($host === null) { + // Relative links and non-network schemes like mailto: have no host to compare continue; } @@ -97,6 +97,28 @@ final class ExternalLinkProcessor } } + /** + * Determines which host a browser would navigate to, which parse_url() doesn't always agree with + * on its own (for example, it finds no host in "https:///example.com" or "///example.com") + */ + private static function getHost(string $url): ?string + { + // Browsers ignore these characters, so links not created by the parser could use them to obscure the host + $url = \str_replace(["\t", "\n", "\r"], '', \trim($url, "\x00..\x20")); + + // For these "special" schemes (and scheme-relative URLs), browsers accept any number of slashes before the + // host, even none, and treat "\" like "/". parse_url() needs exactly "//", so we rewrite the URL to match. + // Without slashes ("https:example.com") a browser may instead resolve the URL relative to the current page, + // but we can't know the page's scheme, so we assume the worst and treat it as a host. + if (\preg_match('~^(?:(?:https?|ftp|wss?):|(?=[/\\\\]{2}))~i', $url, $matches) === 1) { + $url = '//' . \ltrim(\strtr(\substr($url, \strlen($matches[0])), '\\', '/'), '/'); + } + + $host = \parse_url($url, PHP_URL_HOST); + + return \is_string($host) && $host !== '' ? $host : null; + } + /** * @internal This method is only public so we can easily test it. DO NOT USE THIS OUTSIDE OF THIS EXTENSION! * diff --git a/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteBackrefRenderer.php b/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteBackrefRenderer.php index 3b7bc3c..8bd501b 100644 --- a/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteBackrefRenderer.php +++ b/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteBackrefRenderer.php @@ -44,7 +44,13 @@ final class FootnoteBackrefRenderer implements NodeRendererInterface, XmlNodeRen $attrs->append('class', $this->config->get('footnote/backref_class')); $attrs->set('rev', 'footnote'); - $attrs->set('href', \mb_strtolower($node->getReference()->getDestination(), 'UTF-8')); + // The configured prefix is emitted verbatim in the target's id, so only lowercase the label. + $destination = $node->getReference()->getDestination(); + $hrefPrefix = '#' . $this->config->get('footnote/ref_id_prefix'); + $href = \strncmp($destination, $hrefPrefix, \strlen($hrefPrefix)) === 0 + ? $hrefPrefix . \mb_strtolower(\substr($destination, \strlen($hrefPrefix)), 'UTF-8') + : \mb_strtolower($destination, 'UTF-8'); + $attrs->set('href', $href); $attrs->set('role', 'doc-backlink'); $symbol = $this->config->get('footnote/backref_symbol'); diff --git a/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteRefRenderer.php b/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteRefRenderer.php index c0c07d7..e5af10c 100644 --- a/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteRefRenderer.php +++ b/vendor/league/commonmark/src/Extension/Footnote/Renderer/FootnoteRefRenderer.php @@ -40,7 +40,13 @@ final class FootnoteRefRenderer implements NodeRendererInterface, XmlNodeRendere $attrs = $node->data->getData('attributes'); $attrs->append('class', $this->config->get('footnote/ref_class')); - $attrs->set('href', \mb_strtolower($node->getReference()->getDestination(), 'UTF-8')); + // The configured prefix is emitted verbatim in the target's id, so only lowercase the label. + $destination = $node->getReference()->getDestination(); + $hrefPrefix = '#' . $this->config->get('footnote/footnote_id_prefix'); + $href = \strncmp($destination, $hrefPrefix, \strlen($hrefPrefix)) === 0 + ? $hrefPrefix . \mb_strtolower(\substr($destination, \strlen($hrefPrefix)), 'UTF-8') + : \mb_strtolower($destination, 'UTF-8'); + $attrs->set('href', $href); $attrs->set('role', 'doc-noteref'); $idPrefix = $this->config->get('footnote/ref_id_prefix'); diff --git a/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkProcessor.php b/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkProcessor.php index 871aa21..def1e22 100644 --- a/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkProcessor.php +++ b/vendor/league/commonmark/src/Extension/HeadingPermalink/HeadingPermalinkProcessor.php @@ -74,6 +74,10 @@ final class HeadingPermalinkProcessor implements EnvironmentAwareInterface ]); if ($applyToHeading) { + if ($heading->data->has('attributes/id')) { + $slug = $heading->data->get('attributes/id'); + } + $heading->data->set('attributes/id', $idPrefix . $slug); } diff --git a/vendor/league/commonmark/src/Extension/InlinesOnly/InlinesOnlyExtension.php b/vendor/league/commonmark/src/Extension/InlinesOnly/InlinesOnlyExtension.php index 7777510..f85fad5 100644 --- a/vendor/league/commonmark/src/Extension/InlinesOnly/InlinesOnlyExtension.php +++ b/vendor/league/commonmark/src/Extension/InlinesOnly/InlinesOnlyExtension.php @@ -30,6 +30,7 @@ final class InlinesOnlyExtension implements ConfigurableExtensionInterface 'use_underscore' => Expect::bool(true), 'enable_strong' => Expect::bool(true), 'enable_em' => Expect::bool(true), + 'unordered_list_markers' => Expect::listOf('string')->min(1)->default(['*', '+', '-'])->mergeDefaults(false), ])); } diff --git a/vendor/league/commonmark/src/Extension/Table/TableParser.php b/vendor/league/commonmark/src/Extension/Table/TableParser.php index a005f8a..56d2d72 100644 --- a/vendor/league/commonmark/src/Extension/Table/TableParser.php +++ b/vendor/league/commonmark/src/Extension/Table/TableParser.php @@ -61,6 +61,13 @@ final class TableParser extends AbstractBlockContinueParser implements BlockCont private int $remainingAutocompletedCells; + /** + * Whether the current line may be added to the table as a lazy continuation line + * + * @psalm-readonly-allow-private-mutation + */ + private bool $canHaveLazyContinuationLines = false; + /** * @param array<int, string|null> $columns * @param array<int, string> $headerCells @@ -80,7 +87,7 @@ final class TableParser extends AbstractBlockContinueParser implements BlockCont public function canHaveLazyContinuationLines(): bool { - return true; + return $this->canHaveLazyContinuationLines; } public function getBlock(): Table @@ -90,7 +97,11 @@ final class TableParser extends AbstractBlockContinueParser implements BlockCont public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue { - if (\strpos($cursor->getLine(), '|') === false) { + // A line without a pipe can still become a row via lazy continuation. This is only reached when all + // enclosing containers matched; lines whose containers didn't match must not be added lazily. + $this->canHaveLazyContinuationLines = \strpos($cursor->getLine(), '|') === false; + + if ($this->canHaveLazyContinuationLines) { return BlockContinue::none(); } @@ -99,6 +110,8 @@ final class TableParser extends AbstractBlockContinueParser implements BlockCont public function addLine(string $line): void { + $this->canHaveLazyContinuationLines = false; + if ($this->nextIsSeparatorLine) { $this->nextIsSeparatorLine = false; } else { @@ -168,24 +181,28 @@ final class TableParser extends AbstractBlockContinueParser implements BlockCont */ public static function split(string $line): array { - $cursor = new Cursor(\trim($line)); + // Scan raw bytes: the only significant characters are ASCII, and copying the other bytes through one at a + // time reassembles multibyte sequences unchanged. This is several times faster than stepping a Cursor. + $line = \trim($line); + $length = \strlen($line); - if ($cursor->getCurrentCharacter() === '|') { - $cursor->advanceBy(1); + $i = 0; + if ($length > 0 && $line[0] === '|') { + $i = 1; } $cells = []; $sb = ''; - while (! $cursor->isAtEnd()) { - switch ($c = $cursor->getCurrentCharacter()) { + for (; $i < $length; $i++) { + switch ($c = $line[$i]) { case '\\': - if ($cursor->peek() === '|') { + if ($i + 1 < $length && $line[$i + 1] === '|') { // Pipe is special for table parsing. An escaped pipe doesn't result in a new cell, but is // passed down to inline parsing as an unescaped pipe. Note that that applies even for the `\|` // in an input like `\\|` - in other words, table parsing doesn't support escaping backslashes. $sb .= '|'; - $cursor->advanceBy(1); + $i++; } else { // Preserve backslash before other characters or at end of line. $sb .= '\\'; @@ -199,8 +216,6 @@ final class TableParser extends AbstractBlockContinueParser implements BlockCont default: $sb .= $c; } - - $cursor->advanceBy(1); } if ($sb !== '') { diff --git a/vendor/league/commonmark/src/Extension/Table/TableStartParser.php b/vendor/league/commonmark/src/Extension/Table/TableStartParser.php index 1baf29c..87b037a 100644 --- a/vendor/league/commonmark/src/Extension/Table/TableStartParser.php +++ b/vendor/league/commonmark/src/Extension/Table/TableStartParser.php @@ -33,10 +33,12 @@ final class TableStartParser implements BlockStartParserInterface public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart { $paragraph = $parserState->getParagraphContent(); - if ($paragraph === null || \strpos($paragraph, '|') === false) { + if ($paragraph === null) { return BlockStart::none(); } + // Check the (short) current line for a delimiter row before touching the paragraph content. Scanning the + // paragraph on every line would be quadratic, and GFM does not require a pipe in the header row anyway. $columns = self::parseSeparator($cursor); if (\count($columns) === 0) { return BlockStart::none(); @@ -45,8 +47,9 @@ final class TableStartParser implements BlockStartParserInterface $lastLineBreak = \strrpos($paragraph, "\n"); $lastLine = $lastLineBreak === false ? $paragraph : \substr($paragraph, $lastLineBreak + 1); + // Per the GFM spec, the header row must have the same number of cells as the delimiter row $headerCells = TableParser::split($lastLine); - if (\count($headerCells) > \count($columns)) { + if (\count($headerCells) !== \count($columns)) { return BlockStart::none(); } @@ -76,14 +79,20 @@ final class TableStartParser implements BlockStartParserInterface */ private static function parseSeparator(Cursor $cursor): array { + // Scan the raw bytes rather than stepping the Cursor: every character allowed in a delimiter row is ASCII, + // so any multibyte character is simply invalid, and byte indexing avoids the per-character method calls + // (and, on multibyte lines, the character-to-byte offset translation) that the Cursor incurs. + $line = $cursor->getRemainder(); + $length = \strlen($line); + $columns = []; $pipes = 0; $valid = false; - while (! $cursor->isAtEnd()) { - switch ($c = $cursor->getCurrentCharacter()) { + for ($i = 0; $i < $length;) { + switch ($c = $line[$i]) { case '|': - $cursor->advanceBy(1); + $i++; $pipes++; if ($pipes > 1) { // More than one adjacent pipe not allowed @@ -104,17 +113,20 @@ final class TableStartParser implements BlockStartParserInterface $right = false; if ($c === ':') { $left = true; - $cursor->advanceBy(1); + $i++; } - if ($cursor->matchInPlace('/\G-+/') === null) { + $dashes = \strspn($line, '-', $i); + if ($dashes === 0) { // Need at least one dash return []; } - if ($cursor->getCurrentCharacter() === ':') { + $i += $dashes; + + if ($i < $length && $line[$i] === ':') { $right = true; - $cursor->advanceBy(1); + $i++; } $columns[] = self::getAlignment($left, $right); @@ -124,7 +136,7 @@ final class TableStartParser implements BlockStartParserInterface case ' ': case "\t": // White space is allowed between pipes and columns - $cursor->advanceToNextNonSpaceOrTab(); + $i += \strspn($line, " \t", $i); break; default: // Any other character is invalid diff --git a/vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarkerParser.php b/vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarkerParser.php index 30e2731..0d92a12 100644 --- a/vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarkerParser.php +++ b/vendor/league/commonmark/src/Extension/TaskList/TaskListItemMarkerParser.php @@ -18,6 +18,7 @@ use League\CommonMark\Node\Block\Paragraph; use League\CommonMark\Parser\Inline\InlineParserInterface; use League\CommonMark\Parser\Inline\InlineParserMatch; use League\CommonMark\Parser\InlineParserContext; +use League\CommonMark\Util\RegexHelper; final class TaskListItemMarkerParser implements InlineParserInterface { @@ -40,7 +41,9 @@ final class TaskListItemMarkerParser implements InlineParserInterface $cursor->advanceBy(3); - if ($cursor->getNextNonSpaceCharacter() === null) { + // The marker must be followed by whitespace before any other content + $nextCharacter = $cursor->getCurrentCharacter(); + if ($nextCharacter === null || ! RegexHelper::isWhitespace($nextCharacter) || $cursor->getNextNonSpaceCharacter() === null) { $cursor->restoreState($oldState); return false; diff --git a/vendor/league/commonmark/src/Parser/Block/BlockContinueParserInterface.php b/vendor/league/commonmark/src/Parser/Block/BlockContinueParserInterface.php index b6e5472..d0508a4 100644 --- a/vendor/league/commonmark/src/Parser/Block/BlockContinueParserInterface.php +++ b/vendor/league/commonmark/src/Parser/Block/BlockContinueParserInterface.php @@ -38,7 +38,11 @@ interface BlockContinueParserInterface public function isContainer(): bool; /** - * Return whether we are interested in possibly lazily parsing any subsequent lines + * Return whether the current line may be added to this block even though it wasn't continued by tryContinue() + * + * This is checked per line, after tryContinue() (which is skipped if an enclosing container did not match), so + * the answer may depend on the current line. Block start parsers may also consult it to decide whether a new + * block can interrupt this one. */ public function canHaveLazyContinuationLines(): bool; diff --git a/vendor/league/commonmark/src/Reference/ReferenceParser.php b/vendor/league/commonmark/src/Reference/ReferenceParser.php index c01dd21..62cf259 100644 --- a/vendor/league/commonmark/src/Reference/ReferenceParser.php +++ b/vendor/league/commonmark/src/Reference/ReferenceParser.php @@ -76,6 +76,11 @@ final class ReferenceParser */ public function getReferences(): iterable { + if ($this->referenceValid && $this->state === self::TITLE) { + // The title was never closed, so the definition has no title + $this->title = ''; + } + $this->finishReference(); return $this->references; @@ -268,7 +273,9 @@ final class ReferenceParser $title = LinkParserHelper::parsePartialLinkTitle($cursor, $this->titleDelimiter); if ($title === null) { - // Invalid title, stop + // Invalid title, stop. The title collected so far must not be used. + $this->title = ''; + return false; } @@ -293,6 +300,9 @@ final class ReferenceParser $cursor->advanceToNextNonSpaceOrTab(); if (! $cursor->isAtEnd()) { // spec: No further non-whitespace characters may occur on the line. + // The title collected so far must not be used. + $this->title = ''; + return false; } diff --git a/vendor/league/commonmark/src/Util/ArrayCollection.php b/vendor/league/commonmark/src/Util/ArrayCollection.php index 7210770..eae9f99 100644 --- a/vendor/league/commonmark/src/Util/ArrayCollection.php +++ b/vendor/league/commonmark/src/Util/ArrayCollection.php @@ -106,6 +106,8 @@ final class ArrayCollection implements \IteratorAggregate, \Countable, \ArrayAcc * * @phpstan-param int $offset * + * @return mixed|null + * * @phpstan-return T|null */ #[\ReturnTypeWillChange] diff --git a/vendor/league/commonmark/src/Util/LinkParserHelper.php b/vendor/league/commonmark/src/Util/LinkParserHelper.php index 058db7a..3c1a900 100644 --- a/vendor/league/commonmark/src/Util/LinkParserHelper.php +++ b/vendor/league/commonmark/src/Util/LinkParserHelper.php @@ -82,8 +82,10 @@ final class LinkParserHelper public static function parsePartialLinkTitle(Cursor $cursor, string $endDelimiter): ?string { + // spec: a parenthesized title may only contain `(` or `)` if backslash-escaped + $excluded = \preg_quote($endDelimiter === ')' ? '()' : $endDelimiter, '/'); $endDelimiter = \preg_quote($endDelimiter, '/'); - $regex = \sprintf('/(%s|[^%s\x00])*(?:%s)?/', RegexHelper::PARTIAL_ESCAPED_CHAR, $endDelimiter, $endDelimiter); + $regex = \sprintf('/(%s|[^%s\x00])*(?:%s)?/', RegexHelper::PARTIAL_ESCAPED_CHAR, $excluded, $endDelimiter); if (($partialTitle = $cursor->matchInPlace($regex)) === null) { return null; } diff --git a/vendor/league/commonmark/src/Util/RegexHelper.php b/vendor/league/commonmark/src/Util/RegexHelper.php index 9e156f2..3918647 100644 --- a/vendor/league/commonmark/src/Util/RegexHelper.php +++ b/vendor/league/commonmark/src/Util/RegexHelper.php @@ -40,9 +40,9 @@ final class RegexHelper public const PARTIAL_IN_PARENS = '\\((' . self::PARTIAL_ESCAPED_CHAR . '|[^)\x00])*\\)'; public const PARTIAL_REG_CHAR = '[^\\\\()\x00-\x20]'; public const PARTIAL_IN_PARENS_NOSP = '\((' . self::PARTIAL_REG_CHAR . '|' . self::PARTIAL_ESCAPED_CHAR . '|\\\\)*\)'; - public const PARTIAL_TAGNAME = '[a-z][a-z0-9-]*'; + public const PARTIAL_TAGNAME = '[A-Za-z][A-Za-z0-9-]*'; public const PARTIAL_BLOCKTAGNAME = '(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h1|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)'; - public const PARTIAL_ATTRIBUTENAME = '[a-z_:][a-z0-9:._-]*'; + public const PARTIAL_ATTRIBUTENAME = '[A-Za-z_:][A-Za-z0-9:._-]*'; public const PARTIAL_UNQUOTEDVALUE = '[^"\'=<>`\x00-\x20]+'; public const PARTIAL_SINGLEQUOTEDVALUE = '\'[^\']*\''; public const PARTIAL_DOUBLEQUOTEDVALUE = '"[^"]*"'; diff --git a/vendor/nette/schema/composer.json b/vendor/nette/schema/composer.json index fd48db3..69729ee 100644 --- a/vendor/nette/schema/composer.json +++ b/vendor/nette/schema/composer.json @@ -15,21 +15,16 @@ } ], "require": { - "php": "8.1 - 8.5", - "nette/utils": "^4.0" + "php": "7.1 - 8.3", + "nette/utils": "^2.5.7 || ^3.1.5 || ^4.0" }, "require-dev": { - "nette/tester": "^2.6", - "tracy/tracy": "^2.8", - "phpstan/phpstan": "^2.1.39@stable", - "phpstan/extension-installer": "^1.4@stable", - "nette/phpstan-rules": "^1.0" + "nette/tester": "^2.3 || ^2.4", + "tracy/tracy": "^2.7", + "phpstan/phpstan-nette": "^1.0" }, "autoload": { - "classmap": ["src/"], - "psr-4": { - "Nette\\": "src" - } + "classmap": ["src/"] }, "minimum-stability": "dev", "scripts": { @@ -38,12 +33,7 @@ }, "extra": { "branch-alias": { - "dev-master": "1.3-dev" - } - }, - "config": { - "allow-plugins": { - "phpstan/extension-installer": true + "dev-master": "1.2-dev" } } } diff --git a/vendor/nette/schema/readme.md b/vendor/nette/schema/readme.md index 7e52878..1e6714b 100644 --- a/vendor/nette/schema/readme.md +++ b/vendor/nette/schema/readme.md @@ -1,4 +1,5 @@ -# Nette Schema +Nette Schema +************ [![Downloads this Month](https://img.shields.io/packagist/dm/nette/schema.svg)](https://packagist.org/packages/nette/schema) [![Tests](https://github.com/nette/schema/workflows/Tests/badge.svg?branch=master)](https://github.com/nette/schema/actions) @@ -20,7 +21,7 @@ Installation: composer require nette/schema ``` -It requires PHP version 8.1 and supports PHP up to 8.5. +It requires PHP version 7.1 and supports PHP up to 8.3. [Support Me](https://github.com/sponsors/dg) @@ -126,7 +127,7 @@ Expect::null() Expect::array($default = []) ``` -And then all types [supported by the Validators](https://doc.nette.org/validators#toc-expected-types) via `Expect::type('scalar')` or abbreviated `Expect::scalar()`. Also class or interface names are accepted, e.g. `Expect::type('AddressEntity')`. +And then all types [supported by the Validators](https://doc.nette.org/validators#toc-validation-rules) via `Expect::type('scalar')` or abbreviated `Expect::scalar()`. Also class or interface names are accepted, e.g. `Expect::type('AddressEntity')`. You can also use union notation: @@ -438,7 +439,7 @@ Expect::structure([ // creates '$obj = new Info' and writes to $obj->processRefund and $obj->refundAmount ``` -If the class has a constructor, the elements of the structure are passed as named parameters to the constructor: +If the class has a constructor, the elements of the structure are passed as named parameters to the constructor (requires PHP 8): ```php class Info diff --git a/vendor/nette/schema/src/Schema/Context.php b/vendor/nette/schema/src/Schema/Context.php index b42b1ed..b72c48b 100644 --- a/vendor/nette/schema/src/Schema/Context.php +++ b/vendor/nette/schema/src/Schema/Context.php @@ -1,38 +1,40 @@ -<?php declare(strict_types=1); +<?php /** * This file is part of the Nette Framework (https://nette.org) * Copyright (c) 2004 David Grudl (https://davidgrudl.com) */ +declare(strict_types=1); + namespace Nette\Schema; -use function count; +use Nette; -/** - * Accumulates errors and warnings during schema validation and tracks the current path. - */ final class Context { - public bool $skipDefaults = false; + use Nette\SmartObject; - /** @var list<int|string> */ - public array $path = []; + /** @var bool */ + public $skipDefaults = false; - public bool $isKey = false; + /** @var string[] */ + public $path = []; - /** @var list<Message> */ - public array $errors = []; + /** @var bool */ + public $isKey = false; - /** @var list<Message> */ - public array $warnings = []; + /** @var Message[] */ + public $errors = []; - /** @var list<array{DynamicParameter, string, list<int|string>}> */ - public array $dynamics = []; + /** @var Message[] */ + public $warnings = []; + + /** @var array[] */ + public $dynamics = []; - /** @param array<string, mixed> $variables */ public function addError(string $message, string $code, array $variables = []): Message { $variables['isKey'] = $this->isKey; @@ -40,20 +42,18 @@ final class Context } - /** @param array<string, mixed> $variables */ public function addWarning(string $message, string $code, array $variables = []): Message { return $this->warnings[] = new Message($message, $code, $this->path, $variables); } - /** - * Returns a closure that returns true as long as no new errors have been added since the call. - * @return \Closure(): bool - */ + /** @return \Closure(): bool */ public function createChecker(): \Closure { $count = count($this->errors); - return fn(): bool => $count === count($this->errors); + return function () use ($count): bool { + return $count === count($this->errors); + }; } } diff --git a/vendor/nette/schema/src/Schema/DynamicParameter.php b/vendor/nette/schema/src/Schema/DynamicParameter.php index 35ec47d..8dd6105 100644 --- a/vendor/nette/schema/src/Schema/DynamicParameter.php +++ b/vendor/nette/schema/src/Schema/DynamicParameter.php @@ -1,10 +1,12 @@ -<?php declare(strict_types=1); +<?php /** * This file is part of the Nette Framework (https://nette.org) * Copyright (c) 2004 David Grudl (https://davidgrudl.com) */ +declare(strict_types=1); + namespace Nette\Schema; diff --git a/vendor/nette/schema/src/Schema/Elements/AnyOf.php b/vendor/nette/schema/src/Schema/Elements/AnyOf.php index 582cf13..446d6ff 100644 --- a/vendor/nette/schema/src/Schema/Elements/AnyOf.php +++ b/vendor/nette/schema/src/Schema/Elements/AnyOf.php @@ -1,31 +1,33 @@ -<?php declare(strict_types=1); +<?php /** * This file is part of the Nette Framework (https://nette.org) * Copyright (c) 2004 David Grudl (https://davidgrudl.com) */ +declare(strict_types=1); + namespace Nette\Schema\Elements; use Nette; use Nette\Schema\Context; use Nette\Schema\Helpers; use Nette\Schema\Schema; -use function array_merge, array_unique, implode, is_array; -/** - * Schema that accepts any of a fixed set of values or sub-schemas (union type / enumeration). - */ final class AnyOf implements Schema { use Base; + use Nette\SmartObject; - /** @var mixed[] */ - private array $set; + /** @var array */ + private $set; - public function __construct(mixed ...$set) + /** + * @param mixed|Schema ...$set + */ + public function __construct(...$set) { if (!$set) { throw new Nette\InvalidStateException('The enumeration must not be empty.'); @@ -35,9 +37,6 @@ final class AnyOf implements Schema } - /** - * Sets the first variant as the default value (instead of null). - */ public function firstIsDefault(): self { $this->default = $this->set[0]; @@ -45,9 +44,6 @@ final class AnyOf implements Schema } - /** - * Allows null as an accepted value in addition to the defined variants. - */ public function nullable(): self { $this->set[] = null; @@ -55,9 +51,6 @@ final class AnyOf implements Schema } - /** - * Allows the value to be a DynamicParameter as an accepted variant. - */ public function dynamic(): self { $this->set[] = new Type(Nette\Schema\DynamicParameter::class); @@ -68,13 +61,13 @@ final class AnyOf implements Schema /********************* processing ****************d*g**/ - public function normalize(mixed $value, Context $context): mixed + public function normalize($value, Context $context) { return $this->doNormalize($value, $context); } - public function merge(mixed $value, mixed $base): mixed + public function merge($value, $base) { if (is_array($value) && isset($value[Helpers::PreventMerging])) { unset($value[Helpers::PreventMerging]); @@ -85,7 +78,7 @@ final class AnyOf implements Schema } - public function complete(mixed $value, Context $context): mixed + public function complete($value, Context $context) { $isOk = $context->createChecker(); $value = $this->findAlternative($value, $context); @@ -94,19 +87,16 @@ final class AnyOf implements Schema } - private function findAlternative(mixed $value, Context $context): mixed + private function findAlternative($value, Context $context) { $expecteds = $innerErrors = []; foreach ($this->set as $item) { if ($item instanceof Schema) { $dolly = new Context; - $dolly->skipDefaults = $context->skipDefaults; - $dolly->isKey = $context->isKey; $dolly->path = $context->path; $res = $item->complete($item->normalize($value, $dolly), $dolly); if (!$dolly->errors) { $context->warnings = array_merge($context->warnings, $dolly->warnings); - $context->dynamics = array_merge($context->dynamics, $dolly->dynamics); return $res; } @@ -135,20 +125,18 @@ final class AnyOf implements Schema [ 'value' => $value, 'expected' => implode('|', array_unique($expecteds)), - ], + ] ); } - - return null; } - public function completeDefault(Context $context): mixed + public function completeDefault(Context $context) { if ($this->required) { $context->addError( 'The mandatory item %path% is missing.', - Nette\Schema\Message::MissingItem, + Nette\Schema\Message::MissingItem ); return null; } diff --git a/vendor/nette/schema/src/Schema/Elements/Base.php b/vendor/nette/schema/src/Schema/Elements/Base.php index c4e3dd6..4b44514 100644 --- a/vendor/nette/schema/src/Schema/Elements/Base.php +++ b/vendor/nette/schema/src/Schema/Elements/Base.php @@ -1,16 +1,17 @@ -<?php declare(strict_types=1); +<?php /** * This file is part of the Nette Framework (https://nette.org) * Copyright (c) 2004 David Grudl (https://davidgrudl.com) */ +declare(strict_types=1); + namespace Nette\Schema\Elements; use Nette; use Nette\Schema\Context; use Nette\Schema\Helpers; -use function count, is_string; /** @@ -18,18 +19,23 @@ use function count, is_string; */ trait Base { - private bool $required = false; - private mixed $default = null; + /** @var bool */ + private $required = false; - /** @var ?\Closure(mixed): mixed */ - private ?\Closure $before = null; + /** @var mixed */ + private $default; - /** @var list<\Closure(mixed, Context): mixed> */ - private array $transforms = []; - private ?string $deprecated = null; + /** @var callable|null */ + private $before; + + /** @var callable[] */ + private $transforms = []; + + /** @var string|null */ + private $deprecated; - public function default(mixed $value): self + public function default($value): self { $this->default = $value; return $this; @@ -43,44 +49,29 @@ trait Base } - /** - * Sets a pre-normalization callback applied to the raw input value before any validation. - * @param callable(mixed): mixed $handler - */ public function before(callable $handler): self { - $this->before = $handler(...); + $this->before = $handler; return $this; } - /** - * Casts the validated value to a built-in type or instantiates the given class. - */ public function castTo(string $type): self { return $this->transform(Helpers::getCastStrategy($type)); } - /** - * Adds a post-validation transformation callback. The handler may also report errors via Context. - * @param callable(mixed, Context): mixed $handler - */ public function transform(callable $handler): self { - $this->transforms[] = $handler(...); + $this->transforms[] = $handler; return $this; } - /** - * Adds a custom validation assertion; optionally describe it for error messages. - * @param callable(mixed): bool $handler - */ public function assert(callable $handler, ?string $description = null): self { - $expected = $description ?? (is_string($handler) ? "$handler()" : '#' . count($this->transforms)); + $expected = $description ?: (is_string($handler) ? "$handler()" : '#' . count($this->transforms)); return $this->transform(function ($value, Context $context) use ($handler, $description, $expected) { if ($handler($value)) { return $value; @@ -88,16 +79,13 @@ trait Base $context->addError( 'Failed assertion ' . ($description ? "'%assertion%'" : '%assertion%') . ' for %label% %path% with value %value%.', Nette\Schema\Message::FailedAssertion, - ['value' => $value, 'assertion' => $expected], + ['value' => $value, 'assertion' => $expected] ); - return null; }); } - /** - * Marks the item as deprecated; emits a warning with the given message when the item is used. - */ + /** Marks as deprecated */ public function deprecated(string $message = 'The item %path% is deprecated.'): self { $this->deprecated = $message; @@ -105,12 +93,12 @@ trait Base } - public function completeDefault(Context $context): mixed + public function completeDefault(Context $context) { if ($this->required) { $context->addError( 'The mandatory item %path% is missing.', - Nette\Schema\Message::MissingItem, + Nette\Schema\Message::MissingItem ); return null; } @@ -119,7 +107,7 @@ trait Base } - public function doNormalize(mixed $value, Context $context): mixed + public function doNormalize($value, Context $context) { if ($this->before) { $value = ($this->before)($value); @@ -134,13 +122,13 @@ trait Base if ($this->deprecated !== null) { $context->addWarning( $this->deprecated, - Nette\Schema\Message::Deprecated, + Nette\Schema\Message::Deprecated ); } } - private function doTransform(mixed $value, Context $context): mixed + private function doTransform($value, Context $context) { $isOk = $context->createChecker(); foreach ($this->transforms as $handler) { @@ -153,8 +141,8 @@ trait Base } - /** @deprecated use Nette\Schema\Helpers::validateType() */ - private function doValidate(mixed $value, string $expected, Context $context): bool + /** @deprecated use Nette\Schema\Validators::validateType() */ + private function doValidate($value, string $expected, Context $context): bool { $isOk = $context->createChecker(); Helpers::validateType($value, $expected, $context); @@ -162,11 +150,8 @@ trait Base } - /** - * @deprecated use Nette\Schema\Helpers::validateRange() - * @param array{?float, ?float} $range - */ - private static function doValidateRange(mixed $value, array $range, Context $context, string $types = ''): bool + /** @deprecated use Nette\Schema\Validators::validateRange() */ + private static function doValidateRange($value, array $range, Context $context, string $types = ''): bool { $isOk = $context->createChecker(); Helpers::validateRange($value, $range, $context, $types); @@ -175,7 +160,7 @@ trait Base /** @deprecated use doTransform() */ - private function doFinalize(mixed $value, Context $context): mixed + private function doFinalize($value, Context $context) { return $this->doTransform($value, $context); } diff --git a/vendor/nette/schema/src/Schema/Elements/Structure.php b/vendor/nette/schema/src/Schema/Elements/Structure.php index a6cf02d..02ca77b 100644 --- a/vendor/nette/schema/src/Schema/Elements/Structure.php +++ b/vendor/nette/schema/src/Schema/Elements/Structure.php @@ -1,48 +1,51 @@ -<?php declare(strict_types=1); +<?php /** * This file is part of the Nette Framework (https://nette.org) * Copyright (c) 2004 David Grudl (https://davidgrudl.com) */ +declare(strict_types=1); + namespace Nette\Schema\Elements; use Nette; use Nette\Schema\Context; use Nette\Schema\Helpers; use Nette\Schema\Schema; -use function array_diff_key, array_fill_keys, array_key_exists, array_keys, array_map, array_merge, array_pop, array_values, is_array, is_object, strval; final class Structure implements Schema { use Base; + use Nette\SmartObject; /** @var Schema[] */ - private array $items; + private $items; - /** for array|list */ - private ?Schema $otherItems = null; + /** @var Schema|null for array|list */ + private $otherItems; /** @var array{?int, ?int} */ - private array $range = [null, null]; - private bool $skipDefaults = false; + private $range = [null, null]; + + /** @var bool */ + private $skipDefaults = false; - /** @param Schema[] $shape */ - public function __construct(array $shape) + /** + * @param Schema[] $items + */ + public function __construct(array $items) { - (function (Schema ...$items) {})(...array_values($shape)); - $this->items = $shape; + (function (Schema ...$items) {})(...array_values($items)); + $this->items = $items; $this->castTo('object'); $this->required = true; } - /** - * Not supported for structures; always throws. - */ - public function default(mixed $value): self + public function default($value): self { throw new Nette\InvalidStateException('Structure cannot have default value.'); } @@ -63,18 +66,15 @@ final class Structure implements Schema /** - * Allows extra keys not defined in the shape, validating their values against the given type. + * @param string|Schema $type */ - public function otherItems(string|Schema $type = 'mixed'): self + public function otherItems($type = 'mixed'): self { $this->otherItems = $type instanceof Schema ? $type : new Type($type); return $this; } - /** - * When enabled, properties whose value equals the default are omitted from the output. - */ public function skipDefaults(bool $state = true): self { $this->skipDefaults = $state; @@ -82,28 +82,10 @@ final class Structure implements Schema } - /** - * Creates a new structure by merging this shape with additional properties. - * @param Schema[]|self $shape - */ - public function extend(array|self $shape): self - { - $shape = $shape instanceof self ? $shape->items : $shape; - return new self(array_merge($this->items, $shape)); - } - - - /** @return Schema[] */ - public function getShape(): array - { - return $this->items; - } - - /********************* processing ****************d*g**/ - public function normalize(mixed $value, Context $context): mixed + public function normalize($value, Context $context) { if ($prevent = (is_array($value) && isset($value[Helpers::PreventMerging]))) { unset($value[Helpers::PreventMerging]); @@ -133,7 +115,7 @@ final class Structure implements Schema } - public function merge(mixed $value, mixed $base): mixed + public function merge($value, $base) { if (is_array($value) && isset($value[Helpers::PreventMerging])) { unset($value[Helpers::PreventMerging]); @@ -141,26 +123,29 @@ final class Structure implements Schema } if (is_array($value) && is_array($base)) { - $index = $this->otherItems === null ? null : 0; + $index = 0; foreach ($value as $key => $val) { if ($key === $index) { $base[] = $val; $index++; - } else { - $base[$key] = array_key_exists($key, $base) && ($itemSchema = $this->items[$key] ?? $this->otherItems) + } elseif (array_key_exists($key, $base)) { + $itemSchema = $this->items[$key] ?? $this->otherItems; + $base[$key] = $itemSchema ? $itemSchema->merge($val, $base[$key]) - : $val; + : Helpers::merge($val, $base[$key]); + } else { + $base[$key] = $val; } } return $base; } - return $value ?? $base; + return Helpers::merge($value, $base); } - public function complete(mixed $value, Context $context): mixed + public function complete($value, Context $context) { if ($value === null) { $value = []; // is unable to distinguish null from array in NEON @@ -177,7 +162,6 @@ final class Structure implements Schema } - /** @param array<mixed> $value */ private function validateItems(array &$value, Context $context): void { $items = $this->items; @@ -185,13 +169,13 @@ final class Structure implements Schema if ($this->otherItems) { $items += array_fill_keys($extraKeys, $this->otherItems); } else { - $keys = array_map(strval(...), array_keys($items)); + $keys = array_map('strval', array_keys($items)); foreach ($extraKeys as $key) { - $hint = Nette\Utils\Helpers::getSuggestion($keys, (string) $key); + $hint = Nette\Utils\ObjectHelpers::getSuggestion($keys, (string) $key); $context->addError( 'Unexpected item %path%' . ($hint ? ", did you mean '%hint%'?" : '.'), Nette\Schema\Message::UnexpectedItem, - ['hint' => $hint], + ['hint' => $hint] )->path[] = $key; } } @@ -213,19 +197,10 @@ final class Structure implements Schema } - public function completeDefault(Context $context): mixed + public function completeDefault(Context $context) { - if (!$this->required) { - return null; - } - - // the item is missing in the input, do not report it as used deprecated - $deprecated = $this->deprecated; - $this->deprecated = null; - try { - return $this->complete([], $context); - } finally { - $this->deprecated = $deprecated; - } + return $this->required + ? $this->complete([], $context) + : null; } } diff --git a/vendor/nette/schema/src/Schema/Elements/Type.php b/vendor/nette/schema/src/Schema/Elements/Type.php index 880f4bb..c953c6a 100644 --- a/vendor/nette/schema/src/Schema/Elements/Type.php +++ b/vendor/nette/schema/src/Schema/Elements/Type.php @@ -1,32 +1,43 @@ -<?php declare(strict_types=1); +<?php /** * This file is part of the Nette Framework (https://nette.org) * Copyright (c) 2004 David Grudl (https://davidgrudl.com) */ +declare(strict_types=1); + namespace Nette\Schema\Elements; +use Nette; use Nette\Schema\Context; use Nette\Schema\DynamicParameter; use Nette\Schema\Helpers; use Nette\Schema\Schema; -use Nette\Utils\Validators; -use function array_key_exists, array_pop, implode, is_array, str_replace, strpos; final class Type implements Schema { use Base; + use Nette\SmartObject; - private string $type; - private ?Schema $itemsValue = null; - private ?Schema $itemsKey = null; + /** @var string */ + private $type; + + /** @var Schema|null for arrays */ + private $itemsValue; + + /** @var Schema|null for arrays */ + private $itemsKey; /** @var array{?float, ?float} */ - private array $range = [null, null]; - private ?string $pattern = null; - private bool $merge = true; + private $range = [null, null]; + + /** @var string|null */ + private $pattern; + + /** @var bool */ + private $merge = true; public function __construct(string $type) @@ -37,9 +48,6 @@ final class Type implements Schema } - /** - * Allows the value to be null in addition to the declared type. - */ public function nullable(): self { $this->type = 'null|' . $this->type; @@ -47,9 +55,6 @@ final class Type implements Schema } - /** - * Controls whether the default value is merged with the input array (enabled by default). - */ public function mergeDefaults(bool $state = true): self { $this->merge = $state; @@ -57,9 +62,6 @@ final class Type implements Schema } - /** - * Allows the value to be a DynamicParameter, which is recorded for deferred validation. - */ public function dynamic(): self { $this->type = DynamicParameter::class . '|' . $this->type; @@ -82,9 +84,11 @@ final class Type implements Schema /** + * @param string|Schema $valueType + * @param string|Schema|null $keyType * @internal use arrayOf() or listOf() */ - public function items(string|Schema $valueType = 'mixed', string|Schema|null $keyType = null): self + public function items($valueType = 'mixed', $keyType = null): self { $this->itemsValue = $valueType instanceof Schema ? $valueType @@ -96,9 +100,6 @@ final class Type implements Schema } - /** - * Sets a regex pattern the string value must match entirely (anchored to start and end). - */ public function pattern(?string $pattern): self { $this->pattern = $pattern; @@ -109,7 +110,7 @@ final class Type implements Schema /********************* processing ****************d*g**/ - public function normalize(mixed $value, Context $context): mixed + public function normalize($value, Context $context) { if ($prevent = (is_array($value) && isset($value[Helpers::PreventMerging]))) { unset($value[Helpers::PreventMerging]); @@ -140,7 +141,7 @@ final class Type implements Schema } - public function merge(mixed $value, mixed $base): mixed + public function merge($value, $base) { if (is_array($value) && isset($value[Helpers::PreventMerging])) { unset($value[Helpers::PreventMerging]); @@ -167,7 +168,7 @@ final class Type implements Schema } - public function complete(mixed $value, Context $context): mixed + public function complete($value, Context $context) { $merge = $this->merge; if (is_array($value) && isset($value[Helpers::PreventMerging])) { @@ -175,7 +176,7 @@ final class Type implements Schema $merge = false; } - if ($value === null && is_array($this->default) && !Validators::is(null, $this->type)) { + if ($value === null && is_array($this->default)) { $value = []; // is unable to distinguish null from array in NEON } @@ -186,13 +187,13 @@ final class Type implements Schema $isOk() && Helpers::validateRange($value, $this->range, $context, $this->type); $isOk() && $value !== null && $this->pattern !== null && Helpers::validatePattern($value, $this->pattern, $context); $isOk() && is_array($value) && $this->validateItems($value, $context); - $isOk() && $merge && $value !== null && $value = Helpers::merge($value, $this->default); + $isOk() && $merge && $value = Helpers::merge($value, $this->default); $isOk() && $value = $this->doTransform($value, $context); if (!$isOk()) { return null; } - if ($value instanceof DynamicParameter && $this->type !== DynamicParameter::class) { + if ($value instanceof DynamicParameter) { $expected = $this->type . ($this->range === [null, null] ? '' : ':' . implode('..', $this->range)); $context->dynamics[] = [$value, str_replace(DynamicParameter::class . '|', '', $expected), $context->path]; } @@ -200,10 +201,9 @@ final class Type implements Schema } - /** @param array<mixed> $value */ private function validateItems(array &$value, Context $context): void { - if (!($itemsValue = $this->itemsValue)) { + if (!$this->itemsValue) { return; } @@ -211,15 +211,9 @@ final class Type implements Schema foreach ($value as $key => $val) { $context->path[] = $key; $context->isKey = true; - $isKeyOk = $context->createChecker(); $key = $this->itemsKey ? $this->itemsKey->complete($key, $context) : $key; $context->isKey = false; - $keyOk = $isKeyOk(); - $val = $itemsValue->complete($val, $context); - if ($keyOk) { - $res[$key] = $val; - } - + $res[$key] = $this->itemsValue->complete($val, $context); array_pop($context->path); } $value = $res; diff --git a/vendor/nette/schema/src/Schema/Expect.php b/vendor/nette/schema/src/Schema/Expect.php index 44cf25b..f299950 100644 --- a/vendor/nette/schema/src/Schema/Expect.php +++ b/vendor/nette/schema/src/Schema/Expect.php @@ -1,17 +1,18 @@ -<?php declare(strict_types=1); +<?php /** * This file is part of the Nette Framework (https://nette.org) * Copyright (c) 2004 David Grudl (https://davidgrudl.com) */ +declare(strict_types=1); + namespace Nette\Schema; use Nette; use Nette\Schema\Elements\AnyOf; use Nette\Schema\Elements\Structure; use Nette\Schema\Elements\Type; -use function is_object; /** @@ -23,6 +24,7 @@ use function is_object; * @method static Type float($default = null) * @method static Type bool($default = null) * @method static Type null() + * @method static Type array($default = []) * @method static Type list($default = []) * @method static Type mixed($default = null) * @method static Type email($default = null) @@ -30,7 +32,8 @@ use function is_object; */ final class Expect { - /** @param list<mixed> $args */ + use Nette\SmartObject; + public static function __callStatic(string $name, array $args): Type { $type = new Type($name); @@ -42,9 +45,6 @@ final class Expect } - /** - * Creates a schema for a custom type expression (e.g., 'int|string', 'null|float'). - */ public static function type(string $type): Type { return new Type($type); @@ -52,42 +52,38 @@ final class Expect /** - * Creates a union schema that accepts any of the given values or sub-schemas. + * @param mixed|Schema ...$set */ - public static function anyOf(mixed ...$set): AnyOf + public static function anyOf(...$set): AnyOf { return new AnyOf(...$set); } /** - * Creates a structure schema with defined properties; output is stdClass. - * @param Schema[] $shape + * @param Schema[] $items */ - public static function structure(array $shape): Structure + public static function structure(array $items): Structure { - return new Structure($shape); + return new Structure($items); } /** - * Generates a structure schema from a class instance by reflecting its properties or constructor parameters. - * @param array<string, Schema> $items Optional overrides for specific properties. + * @param object $object */ - public static function from(object $object, array $items = []): Structure + public static function from($object, array $items = []): Structure { $ro = new \ReflectionObject($object); - $props = $ro->hasMethod('__construct') - ? $ro->getMethod('__construct')->getParameters() - : $ro->getProperties(); - - foreach ($props as $prop) { - $name = $prop->getName(); - if (!isset($items[$name])) { - $type = Helpers::getPropertyType($prop) ?? 'mixed'; + foreach ($ro->getProperties() as $prop) { + $type = Helpers::getPropertyType($prop) ?? 'mixed'; + $item = &$items[$prop->getName()]; + if (!$item) { $item = new Type($type); - if ($prop instanceof \ReflectionProperty ? $prop->isInitialized($object) : $prop->isOptional()) { - $def = ($prop instanceof \ReflectionProperty ? $prop->getValue($object) : $prop->getDefaultValue()); + if (PHP_VERSION_ID >= 70400 && !$prop->isInitialized($object)) { + $item->required(); + } else { + $def = $prop->getValue($object); if (is_object($def)) { $item = static::from($def); } elseif ($def === null && !Nette\Utils\Validators::is(null, $type)) { @@ -95,10 +91,7 @@ final class Expect } else { $item->default($def); } - } else { - $item->required(); } - $items[$name] = $item; } } @@ -107,32 +100,19 @@ final class Expect /** - * Creates an array schema. When passed Schema elements, behaves like structure() but outputs an array. - * Without Schema elements, creates a plain array type with the given default value. - * @param mixed[] $shape + * @param string|Schema $valueType + * @param string|Schema|null $keyType */ - public static function array(?array $shape = []): Structure|Type - { - $shape ??= []; - return Nette\Utils\Arrays::first($shape) instanceof Schema - ? (new Structure($shape))->castTo('array') - : (new Type('array'))->default($shape); - } - - - /** - * Creates an associative or indexed array schema where every value matches the given type. - */ - public static function arrayOf(string|Schema $valueType, string|Schema|null $keyType = null): Type + public static function arrayOf($valueType, $keyType = null): Type { return (new Type('array'))->items($valueType, $keyType); } /** - * Creates a list schema (sequentially indexed from 0) where every element matches the given type. + * @param string|Schema $type */ - public static function listOf(string|Schema $type): Type + public static function listOf($type): Type { return (new Type('list'))->items($type); } diff --git a/vendor/nette/schema/src/Schema/Helpers.php b/vendor/nette/schema/src/Schema/Helpers.php index e15bf50..3b65322 100644 --- a/vendor/nette/schema/src/Schema/Helpers.php +++ b/vendor/nette/schema/src/Schema/Helpers.php @@ -1,15 +1,16 @@ -<?php declare(strict_types=1); +<?php /** * This file is part of the Nette Framework (https://nette.org) * Copyright (c) 2004 David Grudl (https://davidgrudl.com) */ +declare(strict_types=1); + namespace Nette\Schema; use Nette; use Nette\Utils\Reflection; -use function array_map, count, explode, get_debug_type, implode, in_array, is_array, is_float, is_int, is_object, is_scalar, is_string, is_subclass_of, method_exists, preg_match, preg_quote, preg_replace, preg_replace_callback, settype, str_replace, strlen, trim, var_export; /** @@ -20,12 +21,14 @@ final class Helpers use Nette\StaticClass; public const PreventMerging = '_prevent_merging'; + public const PREVENT_MERGING = self::PreventMerging; /** * Merges dataset. Left has higher priority than right one. + * @return array|string */ - public static function merge(mixed $value, mixed $base): mixed + public static function merge($value, $base) { if (is_array($value) && isset($value[self::PreventMerging])) { unset($value[self::PreventMerging]); @@ -54,19 +57,17 @@ final class Helpers } - /** - * Returns the type of a property or parameter as a string, or null if not determinable. - */ - public static function getPropertyType(\ReflectionProperty|\ReflectionParameter $prop): ?string + public static function getPropertyType(\ReflectionProperty $prop): ?string { - if ($type = Nette\Utils\Type::fromReflection($prop)) { + if (!class_exists(Nette\Utils\Type::class)) { + throw new Nette\NotSupportedException('Expect::from() requires nette/utils 3.x'); + } elseif ($type = Nette\Utils\Type::fromReflection($prop)) { return (string) $type; - } elseif ( - ($prop instanceof \ReflectionProperty) - && ($type = preg_replace('#\s.*#', '', (string) self::parseAnnotation($prop, 'var'))) - ) { + } elseif ($type = preg_replace('#\s.*#', '', (string) self::parseAnnotation($prop, 'var'))) { $class = Reflection::getPropertyDeclaringClass($prop); - return preg_replace_callback('#[\w\\\]+#', fn($m) => Reflection::expandClassName($m[0], $class), $type); + return preg_replace_callback('#[\w\\\\]+#', function ($m) use ($class) { + return Reflection::expandClassName($m[0], $class); + }, $type); } return null; @@ -75,9 +76,9 @@ final class Helpers /** * Returns an annotation value. - * @param \ReflectionClass<object>|\ReflectionProperty $ref + * @param \ReflectionProperty $ref */ - public static function parseAnnotation(\ReflectionClass|\ReflectionProperty $ref, string $name): ?string + public static function parseAnnotation(\Reflector $ref, string $name): ?string { if (!Reflection::areCommentsAvailable()) { throw new Nette\InvalidStateException('You have to enable phpDoc comments in opcode cache.'); @@ -93,28 +94,23 @@ final class Helpers /** - * Formats a value for use in error messages (e.g., 'hello', true, object stdClass). + * @param mixed $value */ - public static function formatValue(mixed $value): string + public static function formatValue($value): string { - if ($value instanceof DynamicParameter) { - return 'dynamic'; - } elseif (is_object($value)) { - return 'object ' . $value::class; + if (is_object($value)) { + return 'object ' . get_class($value); } elseif (is_string($value)) { return "'" . Nette\Utils\Strings::truncate($value, 15, '...') . "'"; } elseif (is_scalar($value)) { - return var_export($value, return: true); + return var_export($value, true); } else { - return get_debug_type($value); + return strtolower(gettype($value)); } } - /** - * Adds a TypeMismatch error to the context if the value does not match the expected type. - */ - public static function validateType(mixed $value, string $expected, Context $context): void + public static function validateType($value, string $expected, Context $context): void { if (!Nette\Utils\Validators::is($value, $expected)) { $expected = str_replace(DynamicParameter::class . '|', '', $expected); @@ -122,22 +118,18 @@ final class Helpers $context->addError( 'The %label% %path% expects to be %expected%, %value% given.', Message::TypeMismatch, - ['value' => $value, 'expected' => $expected], + ['value' => $value, 'expected' => $expected] ); } } - /** - * Adds a range error to the context if the value (or its length for strings/arrays) is outside the given range. - * @param array{?float, ?float} $range - */ - public static function validateRange(mixed $value, array $range, Context $context, string $types = ''): void + public static function validateRange($value, array $range, Context $context, string $types = ''): void { if (is_array($value) || is_string($value)) { [$length, $label] = is_array($value) ? [count($value), 'items'] - : (in_array('unicode', explode('|', $types), strict: true) + : (in_array('unicode', explode('|', $types), true) ? [Nette\Utils\Strings::length($value), 'characters'] : [strlen($value), 'bytes']); @@ -145,87 +137,62 @@ final class Helpers $context->addError( "The length of %label% %path% expects to be in range %expected%, %length% $label given.", Message::LengthOutOfRange, - ['value' => $value, 'length' => $length, 'expected' => implode('..', $range)], + ['value' => $value, 'length' => $length, 'expected' => implode('..', $range)] ); } } elseif ((is_int($value) || is_float($value)) && !self::isInRange($value, $range)) { $context->addError( 'The %label% %path% expects to be in range %expected%, %value% given.', Message::ValueOutOfRange, - ['value' => $value, 'expected' => implode('..', $range)], + ['value' => $value, 'expected' => implode('..', $range)] ); } } - /** - * Checks whether a value falls within the given [min, max] range (null means no bound). - * @param array{?float, ?float} $range - */ - public static function isInRange(mixed $value, array $range): bool + public static function isInRange($value, array $range): bool { return ($range[0] === null || $value >= $range[0]) && ($range[1] === null || $value <= $range[1]); } - /** - * Adds a PatternMismatch error to the context if the value does not match the pattern. - */ public static function validatePattern(string $value, string $pattern, Context $context): void { if (!preg_match("\x01^(?:$pattern)$\x01Du", $value)) { $context->addError( "The %label% %path% expects to match pattern '%pattern%', %value% given.", Message::PatternMismatch, - ['value' => $value, 'pattern' => $pattern], + ['value' => $value, 'pattern' => $pattern] ); } } - /** - * Returns a closure that casts a value to the given type (built-in, backed enum, class with constructor, or plain class). - * @return \Closure(mixed, Context): mixed - */ public static function getCastStrategy(string $type): \Closure { - if (Nette\Utils\Validators::isBuiltinType($type)) { + if (Nette\Utils\Reflection::isBuiltinType($type)) { return static function ($value) use ($type) { settype($value, $type); return $value; }; - - } elseif (is_subclass_of($type, \BackedEnum::class)) { - return static function ($value, Context $context) use ($type) { - try { - return $type::from($value); - } catch (\TypeError | \ValueError) { - $context->addError( - 'The %label% %path% expects to be %expected%, %value% given.', - Message::TypeMismatch, - ['value' => $value, 'expected' => implode('|', array_map(fn(\BackedEnum $case) => self::formatValue($case->value), $type::cases()))], - ); - return null; + } elseif (method_exists($type, '__construct')) { + return static function ($value) use ($type) { + if (PHP_VERSION_ID < 80000 && is_array($value)) { + throw new Nette\NotSupportedException("Creating $type objects is supported since PHP 8.0"); } + return is_array($value) + ? new $type(...$value) + : new $type($value); + }; + } else { + return static function ($value) use ($type) { + $object = new $type; + foreach ($value as $k => $v) { + $object->$k = $v; + } + return $object; }; - - } elseif (is_subclass_of($type, \UnitEnum::class)) { - throw new Nette\InvalidStateException("Cannot cast value to pure enum $type."); } - - $factory = method_exists($type, '__construct') - ? static fn($value) => is_array($value) || $value instanceof \stdClass - ? new $type(...(array) $value) - : new $type($value) - : static fn($value) => Nette\Utils\Arrays::toObject((array) $value, new $type); - - return static function ($value) use ($factory, $type) { - try { - return $factory($value); - } catch (\Error $e) { - throw new Nette\InvalidStateException("Unable to cast value to $type: " . $e->getMessage(), 0, $e); - } - }; } } diff --git a/vendor/nette/schema/src/Schema/Message.php b/vendor/nette/schema/src/Schema/Message.php index f06f172..6f7c2ec 100644 --- a/vendor/nette/schema/src/Schema/Message.php +++ b/vendor/nette/schema/src/Schema/Message.php @@ -1,20 +1,21 @@ -<?php declare(strict_types=1); +<?php /** * This file is part of the Nette Framework (https://nette.org) * Copyright (c) 2004 David Grudl (https://davidgrudl.com) */ +declare(strict_types=1); + namespace Nette\Schema; -use function array_key_exists, implode, preg_replace_callback; +use Nette; -/** - * Represents a single validation error or warning with a message template, error code, path, and variables. - */ final class Message { + use Nette\SmartObject; + /** variables: {value: mixed, expected: string} */ public const TypeMismatch = 'schema.typeMismatch'; @@ -39,45 +40,38 @@ final class Message /** no variables */ public const Deprecated = 'schema.deprecated'; - /** @deprecated use Message::TypeMismatch */ + /** Deprecated */ public const TYPE_MISMATCH = self::TypeMismatch; - - /** @deprecated use Message::ValueOutOfRange */ public const VALUE_OUT_OF_RANGE = self::ValueOutOfRange; - - /** @deprecated use Message::LengthOutOfRange */ public const LENGTH_OUT_OF_RANGE = self::LengthOutOfRange; - - /** @deprecated use Message::PatternMismatch */ public const PATTERN_MISMATCH = self::PatternMismatch; - - /** @deprecated use Message::FailedAssertion */ public const FAILED_ASSERTION = self::FailedAssertion; - - /** @deprecated use Message::MissingItem */ public const MISSING_ITEM = self::MissingItem; - - /** @deprecated use Message::UnexpectedItem */ public const UNEXPECTED_ITEM = self::UnexpectedItem; - - /** @deprecated use Message::Deprecated */ public const DEPRECATED = self::Deprecated; + /** @var string */ + public $message; - public function __construct( - public string $message, - public string $code, - /** @var list<int|string> */ - public array $path, - /** @var array<string, mixed> */ - public array $variables = [], - ) { + /** @var string */ + public $code; + + /** @var string[] */ + public $path; + + /** @var string[] */ + public $variables; + + + public function __construct(string $message, string $code, array $path, array $variables = []) + { + $this->message = $message; + $this->code = $code; + $this->path = $path; + $this->variables = $variables; } - /** - * Formats the message template by substituting %variable% placeholders with their values. - */ public function toString(): string { $vars = $this->variables; @@ -89,9 +83,7 @@ final class Message return preg_replace_callback('~( ?)%(\w+)%~', function ($m) use ($vars) { [, $space, $key] = $m; - return array_key_exists($key, $vars) - ? ($vars[$key] === null ? '' : $space . $vars[$key]) - : $m[0]; + return $vars[$key] === null ? '' : $space . $vars[$key]; }, $this->message); } } diff --git a/vendor/nette/schema/src/Schema/Processor.php b/vendor/nette/schema/src/Schema/Processor.php index 3ce576a..a10a0ef 100644 --- a/vendor/nette/schema/src/Schema/Processor.php +++ b/vendor/nette/schema/src/Schema/Processor.php @@ -1,10 +1,12 @@ -<?php declare(strict_types=1); +<?php /** * This file is part of the Nette Framework (https://nette.org) * Copyright (c) 2004 David Grudl (https://davidgrudl.com) */ +declare(strict_types=1); + namespace Nette\Schema; use Nette; @@ -15,16 +17,19 @@ use Nette; */ final class Processor { - /** @var list<\Closure(Context): void> */ - public array $onNewContext = []; - private Context $context; - private bool $skipDefaults = false; + use Nette\SmartObject; + + /** @var array */ + public $onNewContext = []; + + /** @var Context|null */ + private $context; + + /** @var bool */ + private $skipDefaults; - /** - * When enabled, properties with default values are omitted from the output. - */ - public function skipDefaults(bool $value = true): void + public function skipDefaults(bool $value = true) { $this->skipDefaults = $value; } @@ -32,60 +37,58 @@ final class Processor /** * Normalizes and validates data. Result is a clean completed data. + * @return mixed * @throws ValidationException */ - public function process(Schema $schema, mixed $data): mixed + public function process(Schema $schema, $data) { $this->createContext(); $data = $schema->normalize($data, $this->context); - $this->throwErrors(); + $this->throwsErrors(); $data = $schema->complete($data, $this->context); - $this->throwErrors(); + $this->throwsErrors(); return $data; } /** * Normalizes and validates and merges multiple data. Result is a clean completed data. - * @param list<mixed> $dataset + * @return mixed * @throws ValidationException */ - public function processMultiple(Schema $schema, array $dataset): mixed + public function processMultiple(Schema $schema, array $dataset) { $this->createContext(); $flatten = null; $first = true; foreach ($dataset as $data) { $data = $schema->normalize($data, $this->context); - $this->throwErrors(); + $this->throwsErrors(); $flatten = $first ? $data : $schema->merge($data, $flatten); $first = false; } $data = $schema->complete($flatten, $this->context); - $this->throwErrors(); + $this->throwsErrors(); return $data; } /** - * Returns all deprecation warnings collected during the last processing run. - * @return list<string> + * @return string[] */ public function getWarnings(): array { $res = []; - if (isset($this->context)) { - foreach ($this->context->warnings as $message) { - $res[] = $message->toString(); - } + foreach ($this->context->warnings as $message) { + $res[] = $message->toString(); } return $res; } - private function throwErrors(): void + private function throwsErrors(): void { if ($this->context->errors) { throw new ValidationException(null, $this->context->errors); @@ -93,10 +96,10 @@ final class Processor } - private function createContext(): void + private function createContext() { $this->context = new Context; $this->context->skipDefaults = $this->skipDefaults; - Nette\Utils\Arrays::invoke($this->onNewContext, $this->context); + $this->onNewContext($this->context); } } diff --git a/vendor/nette/schema/src/Schema/Schema.php b/vendor/nette/schema/src/Schema/Schema.php index 619ebcf..bbd8bd0 100644 --- a/vendor/nette/schema/src/Schema/Schema.php +++ b/vendor/nette/schema/src/Schema/Schema.php @@ -1,38 +1,36 @@ -<?php declare(strict_types=1); +<?php /** * This file is part of the Nette Framework (https://nette.org) * Copyright (c) 2004 David Grudl (https://davidgrudl.com) */ +declare(strict_types=1); + namespace Nette\Schema; -/** - * Defines the contract for schema elements used in data validation and normalization. - */ interface Schema { /** - * Applies pre-processing transformations to the raw input value (e.g., via before() hooks). + * Normalization. * @return mixed */ - function normalize(mixed $value, Context $context); + function normalize($value, Context $context); /** - * Merges two normalized values, with $value taking priority over $base. + * Merging. * @return mixed */ - function merge(mixed $value, mixed $base); + function merge($value, $base); /** - * Validates the value and applies defaults, transforms, and assertions. + * Validation and finalization. * @return mixed */ - function complete(mixed $value, Context $context); + function complete($value, Context $context); /** - * Returns the default value, or adds a missing-item error if the field is required. * @return mixed */ function completeDefault(Context $context); diff --git a/vendor/nette/schema/src/Schema/ValidationException.php b/vendor/nette/schema/src/Schema/ValidationException.php index cefca43..04c581f 100644 --- a/vendor/nette/schema/src/Schema/ValidationException.php +++ b/vendor/nette/schema/src/Schema/ValidationException.php @@ -1,10 +1,12 @@ -<?php declare(strict_types=1); +<?php /** * This file is part of the Nette Framework (https://nette.org) * Copyright (c) 2004 David Grudl (https://davidgrudl.com) */ +declare(strict_types=1); + namespace Nette\Schema; use Nette; @@ -15,18 +17,22 @@ use Nette; */ class ValidationException extends Nette\InvalidStateException { - public function __construct( - ?string $message, - /** @var list<Message> */ - private readonly array $messages = [], - ) { - parent::__construct($message ?? $messages[0]->toString()); + /** @var Message[] */ + private $messages; + + + /** + * @param Message[] $messages + */ + public function __construct(?string $message, array $messages = []) + { + parent::__construct($message ?: $messages[0]->toString()); + $this->messages = $messages; } /** - * Returns all validation error messages as formatted strings. - * @return list<string> + * @return string[] */ public function getMessages(): array { @@ -40,8 +46,7 @@ class ValidationException extends Nette\InvalidStateException /** - * Returns all validation error messages as Message objects. - * @return list<Message> + * @return Message[] */ public function getMessageObjects(): array { diff --git a/vendor/nette/utils/composer.json b/vendor/nette/utils/composer.json index 7014841..d85a619 100644 --- a/vendor/nette/utils/composer.json +++ b/vendor/nette/utils/composer.json @@ -15,14 +15,12 @@ } ], "require": { - "php": "8.2 - 8.5" + "php": "8.0 - 8.6" }, "require-dev": { "nette/tester": "^2.5", "tracy/tracy": "^2.9", - "phpstan/phpstan": "^2.1@stable", - "phpstan/extension-installer": "^1.4@stable", - "nette/phpstan-rules": "^1.0", + "phpstan/phpstan-nette": "^2.0@stable", "jetbrains/phpstorm-attributes": "^1.2" }, "conflict": { @@ -30,7 +28,7 @@ "nette/schema": "<1.2.2" }, "suggest": { - "ext-iconv": "to use Strings::chr(), ord() and reverse()", + "ext-iconv": "to use Strings::webalize(), toAscii(), chr() and reverse()", "ext-json": "to use Nette\\Utils\\Json", "ext-intl": "to use Strings::webalize(), toAscii(), normalize() and compare()", "ext-mbstring": "to use Strings::lower() etc...", @@ -50,12 +48,7 @@ }, "extra": { "branch-alias": { - "dev-master": "4.1-dev" - } - }, - "config": { - "allow-plugins": { - "phpstan/extension-installer": true + "dev-master": "4.0-dev" } } } diff --git a/vendor/nette/utils/readme.md b/vendor/nette/utils/readme.md index 8c717be..481ea25 100644 --- a/vendor/nette/utils/readme.md +++ b/vendor/nette/utils/readme.md @@ -41,7 +41,7 @@ The recommended way to install is via Composer: composer require nette/utils ``` -Nette Utils 4.1 is compatible with PHP 8.2 to 8.5. +Nette Utils 4.0 is compatible with PHP 8.0 to 8.6.  <!----> diff --git a/vendor/nette/utils/src/HtmlStringable.php b/vendor/nette/utils/src/HtmlStringable.php index c9600d2..41418e9 100644 --- a/vendor/nette/utils/src/HtmlStringable.php +++ b/vendor/nette/utils/src/HtmlStringable.php @@ -8,13 +8,10 @@ namespace Nette; -/** - * Represents object convertible to HTML string. - */ interface HtmlStringable { /** - * Returns string in HTML format. + * Returns string in HTML format */ function __toString(): string; } diff --git a/vendor/nette/utils/src/Iterators/CachingIterator.php b/vendor/nette/utils/src/Iterators/CachingIterator.php index 4c2830c..1b6fd9b 100644 --- a/vendor/nette/utils/src/Iterators/CachingIterator.php +++ b/vendor/nette/utils/src/Iterators/CachingIterator.php @@ -11,19 +11,16 @@ use Nette; /** - * Enhanced caching iterator with first/last/counter tracking. + * Smarter caching iterator. * - * @template TKey - * @template TValue - * @extends \CachingIterator<TKey, TValue, \Iterator<TKey, TValue>> * @property-read bool $first * @property-read bool $last * @property-read bool $empty * @property-read bool $odd * @property-read bool $even * @property-read int $counter - * @property-read TKey $nextKey - * @property-read TValue $nextValue + * @property-read mixed $nextKey + * @property-read mixed $nextValue */ class CachingIterator extends \CachingIterator implements \Countable { @@ -32,7 +29,6 @@ class CachingIterator extends \CachingIterator implements \Countable private int $counter = 0; - /** @param iterable<TKey, TValue>|\stdClass $iterable */ public function __construct(iterable|\stdClass $iterable) { $iterable = $iterable instanceof \stdClass @@ -60,30 +56,45 @@ class CachingIterator extends \CachingIterator implements \Countable } + /** + * Is the iterator empty? + */ public function isEmpty(): bool { return $this->counter === 0; } + /** + * Is the counter odd? + */ public function isOdd(): bool { return $this->counter % 2 === 1; } + /** + * Is the counter even? + */ public function isEven(): bool { return $this->counter % 2 === 0; } + /** + * Returns the counter. + */ public function getCounter(): int { return $this->counter; } + /** + * Returns the count of elements. + */ public function count(): int { $inner = $this->getInnerIterator(); @@ -118,14 +129,18 @@ class CachingIterator extends \CachingIterator implements \Countable } - /** @return TKey */ + /** + * Returns the next key. + */ public function getNextKey(): mixed { return $this->getInnerIterator()->key(); } - /** @return TValue */ + /** + * Returns the next element. + */ public function getNextValue(): mixed { return $this->getInnerIterator()->current(); diff --git a/vendor/nette/utils/src/Iterators/Mapper.php b/vendor/nette/utils/src/Iterators/Mapper.php index a9cfba0..5d63343 100644 --- a/vendor/nette/utils/src/Iterators/Mapper.php +++ b/vendor/nette/utils/src/Iterators/Mapper.php @@ -13,13 +13,14 @@ namespace Nette\Iterators; */ class Mapper extends \IteratorIterator { - private \Closure $callback; + /** @var callable */ + private $callback; public function __construct(\Traversable $iterator, callable $callback) { parent::__construct($iterator); - $this->callback = $callback(...); + $this->callback = $callback; } diff --git a/vendor/nette/utils/src/SmartObject.php b/vendor/nette/utils/src/SmartObject.php index d9742c8..d1a06e6 100644 --- a/vendor/nette/utils/src/SmartObject.php +++ b/vendor/nette/utils/src/SmartObject.php @@ -20,7 +20,6 @@ use Nette\Utils\ObjectHelpers; trait SmartObject { /** - * @param mixed[] $args * @return mixed * @throws MemberAccessException */ @@ -46,8 +45,6 @@ trait SmartObject /** - * @param mixed[] $args - * @return never * @throws MemberAccessException */ public static function __callStatic(string $name, array $args) diff --git a/vendor/nette/utils/src/StaticClass.php b/vendor/nette/utils/src/StaticClass.php index e88a74b..05d94ce 100644 --- a/vendor/nette/utils/src/StaticClass.php +++ b/vendor/nette/utils/src/StaticClass.php @@ -9,7 +9,7 @@ namespace Nette; /** - * Prevents instantiation. + * Static class. */ trait StaticClass { @@ -19,4 +19,14 @@ trait StaticClass private function __construct() { } + + + /** + * Call to undefined static method. + * @throws MemberAccessException + */ + public static function __callStatic(string $name, array $args): mixed + { + Utils\ObjectHelpers::strictStaticCall(static::class, $name); + } } diff --git a/vendor/nette/utils/src/Translator.php b/vendor/nette/utils/src/Translator.php index 85c2e1b..16e6f87 100644 --- a/vendor/nette/utils/src/Translator.php +++ b/vendor/nette/utils/src/Translator.php @@ -9,7 +9,7 @@ namespace Nette\Localization; /** - * Translation provider. + * Translator adapter. */ interface Translator { diff --git a/vendor/nette/utils/src/Utils/ArrayHash.php b/vendor/nette/utils/src/Utils/ArrayHash.php index cb19b36..49bad4e 100644 --- a/vendor/nette/utils/src/Utils/ArrayHash.php +++ b/vendor/nette/utils/src/Utils/ArrayHash.php @@ -12,7 +12,7 @@ use function count, is_array, is_scalar, sprintf; /** - * Array-like object with property access. + * Provides objects to work as array. * @template T * @implements \IteratorAggregate<array-key, T> * @implements \ArrayAccess<array-key, T> @@ -37,6 +37,7 @@ class ArrayHash extends \stdClass implements \ArrayAccess, \Countable, \Iterator /** + * Returns an iterator over all items. * @return \Iterator<array-key, T> */ public function &getIterator(): \Iterator @@ -47,6 +48,9 @@ class ArrayHash extends \stdClass implements \ArrayAccess, \Countable, \Iterator } + /** + * Returns items count. + */ public function count(): int { return count((array) $this); @@ -73,7 +77,8 @@ class ArrayHash extends \stdClass implements \ArrayAccess, \Countable, \Iterator * @param array-key $key * @return T */ - public function offsetGet($key): mixed + #[\ReturnTypeWillChange] + public function offsetGet($key) { return $this->$key; } diff --git a/vendor/nette/utils/src/Utils/ArrayList.php b/vendor/nette/utils/src/Utils/ArrayList.php index 90b3ec0..c660b77 100644 --- a/vendor/nette/utils/src/Utils/ArrayList.php +++ b/vendor/nette/utils/src/Utils/ArrayList.php @@ -8,18 +8,19 @@ namespace Nette\Utils; use Nette; -use function array_splice, array_unshift, count, is_int; +use function count, is_int; /** - * Generic list with integer indices. + * Provides the base class for a generic list (items can be accessed by index). * @template T * @implements \IteratorAggregate<int, T> * @implements \ArrayAccess<int, T> */ class ArrayList implements \ArrayAccess, \Countable, \IteratorAggregate { - /** @var list<T> */ + use Nette\SmartObject; + private array $list = []; @@ -40,6 +41,7 @@ class ArrayList implements \ArrayAccess, \Countable, \IteratorAggregate /** + * Returns an iterator over all items. * @return \Iterator<int, T> */ public function &getIterator(): \Iterator @@ -50,6 +52,9 @@ class ArrayList implements \ArrayAccess, \Countable, \IteratorAggregate } + /** + * Returns items count. + */ public function count(): int { return count($this->list); @@ -58,7 +63,7 @@ class ArrayList implements \ArrayAccess, \Countable, \IteratorAggregate /** * Replaces or appends an item. - * @param ?int $index + * @param int|null $index * @param T $value * @throws Nette\OutOfRangeException */ @@ -123,8 +128,8 @@ class ArrayList implements \ArrayAccess, \Countable, \IteratorAggregate */ public function prepend(mixed $value): void { - // route the value through offsetSet() first so a validation added in a subclass isn't bypassed - $this->offsetSet(null, $value); - array_unshift($this->list, ...array_splice($this->list, -1)); + $first = array_slice($this->list, 0, 1); + $this->offsetSet(0, $value); + array_splice($this->list, 1, 0, $first); } } diff --git a/vendor/nette/utils/src/Utils/Arrays.php b/vendor/nette/utils/src/Utils/Arrays.php index 51b346f..85ea1ed 100644 --- a/vendor/nette/utils/src/Utils/Arrays.php +++ b/vendor/nette/utils/src/Utils/Arrays.php @@ -9,12 +9,12 @@ namespace Nette\Utils; use JetBrains\PhpStorm\Language; use Nette; -use function array_combine, array_intersect_key, array_is_list, array_key_exists, array_key_first, array_key_last, array_keys, array_reverse, array_search, array_slice, array_walk_recursive, count, func_num_args, in_array, is_array, is_int, is_object, key, preg_split; -use const PREG_GREP_INVERT, PREG_SPLIT_DELIM_CAPTURE, PREG_SPLIT_NO_EMPTY; +use function array_key_exists, count, func_num_args, is_array, is_int, is_object; +use const PHP_VERSION_ID, PREG_SPLIT_DELIM_CAPTURE, PREG_SPLIT_NO_EMPTY; /** - * Array manipulation utilities. + * Array tools library. */ class Arrays { @@ -70,14 +70,14 @@ class Arrays /** - * Recursively merges two arrays. Useful for merging tree structures. Behaves like the + operator: - * key/value pairs from the second array are added to the first, with the first array's values taking - * precedence on key collisions. Nested arrays are merged recursively instead of replaced. + * Recursively merges two fields. It is useful, for example, for merging tree structures. It behaves as + * the + operator for array, ie. it adds a key/value pair from the second array to the first one and retains + * the value from the first array in the case of a key collision. * @template T1 * @template T2 * @param array<T1> $array1 * @param array<T2> $array2 - * @return array<T1|T2|array<mixed>> + * @return array<T1|T2> */ public static function mergeTree(array $array1, array $array2): array { @@ -94,7 +94,6 @@ class Arrays /** * Returns zero-indexed position of given array key. Returns null if key is not found. - * @param array<mixed> $array */ public static function getKeyOffset(array $array, string|int $key): ?int { @@ -103,10 +102,9 @@ class Arrays /** - * @param array<mixed> $array * @deprecated use getKeyOffset() */ - public static function searchKey(array $array, string|int $key): ?int + public static function searchKey(array $array, $key): ?int { return self::getKeyOffset($array, $key); } @@ -114,23 +112,20 @@ class Arrays /** * Tests an array for the presence of value. - * @param array<mixed> $array */ public static function contains(array $array, mixed $value): bool { - return in_array($value, $array, strict: true); + return in_array($value, $array, true); } /** - * Returns the first item (matching the specified predicate if given). If there is no such item, it returns result of invoking $else or null. + * Returns the first item (matching the predicate if given). If there is no such item, returns the result of $else or null. * @template K of int|string * @template V - * @template E * @param array<K, V> $array * @param ?callable(V, K, array<K, V>): bool $predicate - * @param ?callable(): E $else - * @return ($else is null ? ?V : V|E) + * @return ?V */ public static function first(array $array, ?callable $predicate = null, ?callable $else = null): mixed { @@ -142,14 +137,12 @@ class Arrays /** - * Returns the last item (matching the specified predicate if given). If there is no such item, it returns result of invoking $else or null. + * Returns the last item (matching the predicate if given). If there is no such item, returns the result of $else or null. * @template K of int|string * @template V - * @template E * @param array<K, V> $array * @param ?callable(V, K, array<K, V>): bool $predicate - * @param ?callable(): E $else - * @return ($else is null ? ?V : V|E) + * @return ?V */ public static function last(array $array, ?callable $predicate = null, ?callable $else = null): mixed { @@ -199,10 +192,8 @@ class Arrays /** - * Inserts the contents of the $inserted array into the $array immediately before the $key. + * Inserts the contents of the $inserted array into the $array immediately after the $key. * If $key is null (or does not exist), it is inserted at the beginning. - * @param array<mixed> $array - * @param array<mixed> $inserted */ public static function insertBefore(array &$array, string|int|null $key, array $inserted): void { @@ -214,10 +205,8 @@ class Arrays /** - * Inserts the contents of the $inserted array into the $array immediately after the $key. + * Inserts the contents of the $inserted array into the $array before the $key. * If $key is null (or does not exist), it is inserted at the end. - * @param array<mixed> $array - * @param array<mixed> $inserted */ public static function insertAfter(array &$array, string|int|null $key, array $inserted): void { @@ -233,7 +222,6 @@ class Arrays /** * Renames key in array. - * @param array<mixed> $array */ public static function renameKey(array &$array, string|int $oldKey, string|int $newKey): bool { @@ -270,15 +258,13 @@ class Arrays /** * Transforms multidimensional array to flat array. - * @param array<mixed> $array - * @return array<mixed> */ public static function flatten(array $array, bool $preserveKeys = false): array { $res = []; $cb = $preserveKeys ? function ($v, $k) use (&$res): void { $res[$k] = $v; } - : function ($v) use (&$res): void { $res[] = $v; }; + : function ($v) use (&$res): void { $res[] = $v; }; array_walk_recursive($array, $cb); return $res; } @@ -290,24 +276,26 @@ class Arrays */ public static function isList(mixed $value): bool { - return is_array($value) && array_is_list($value); + return is_array($value) && ( + PHP_VERSION_ID < 80100 + ? !$value || array_keys($value) === range(0, count($value) - 1) + : array_is_list($value) + ); } /** - * Transforms a flat array of rows into an associative tree using a path expression like 'field|field[]field->field=field'. - * @param array<mixed> $array - * @param string|list<string> $path - * @return array<mixed>|\stdClass + * Reformats table to associative tree. Path looks like 'field|field[]field->field=field'. + * @param string|string[] $path */ - public static function associate(array $array, string|array $path): array|\stdClass + public static function associate(array $array, $path): array|\stdClass { $parts = is_array($path) ? $path - : preg_split('#(\[]|->|=|\|)#', $path, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); + : preg_split('#(\[\]|->|=|\|)#', $path, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); if (!$parts || $parts === ['->'] || $parts[0] === '=' || $parts[0] === '|') { - throw new Nette\InvalidArgumentException("Invalid path '" . (is_array($path) ? implode('', $path) : $path) . "'."); + throw new Nette\InvalidArgumentException("Invalid path '$path'."); } $res = $parts[0] === '->' ? new \stdClass : []; @@ -326,8 +314,6 @@ class Arrays $x = $row[$parts[$i]]; $row = null; } - break; // '=' is always the final operation - } elseif ($part === '->') { if (isset($parts[++$i])) { if ($x === null) { @@ -335,6 +321,7 @@ class Arrays } $x = &$x->{$row[$parts[$i]]}; + } else { $row = is_object($rowOrig) ? $rowOrig : (object) $row; } @@ -353,9 +340,7 @@ class Arrays /** - * Converts array to associative: items with numeric keys are converted to keys, with $filling as their value. - * @param array<mixed> $array - * @return array<string, mixed> + * Normalizes array to associative array. Replace numeric keys with their values, the new value will be $filling. */ public static function normalize(array $array, mixed $filling = null): array { @@ -498,10 +483,9 @@ class Arrays /** * Invokes all callbacks and returns array of results. - * @param iterable<callable> $callbacks - * @return array<mixed> + * @param callable[] $callbacks */ - public static function invoke(iterable $callbacks, mixed ...$args): array + public static function invoke(iterable $callbacks, ...$args): array { $res = []; foreach ($callbacks as $k => $cb) { @@ -514,10 +498,9 @@ class Arrays /** * Invokes method on every object in an array and returns array of results. - * @param iterable<object> $objects - * @return array<mixed> + * @param object[] $objects */ - public static function invokeMethod(iterable $objects, string $method, mixed ...$args): array + public static function invokeMethod(iterable $objects, string $method, ...$args): array { $res = []; foreach ($objects as $k => $obj) { @@ -531,7 +514,6 @@ class Arrays /** * Copies the elements of the $array array to the $object object and then returns it. * @template T of object - * @param iterable<mixed> $array * @param T $object * @return T */ @@ -550,12 +532,13 @@ class Arrays */ public static function toKey(mixed $value): int|string { - return key(@[$value => null]); + return key(@[$value => null]); // @ null as an array offset is deprecated in PHP 8.5 } /** - * Returns a copy of $array where every item is cast to string and wrapped with $prefix and $suffix. + * Returns copy of the $array where every item is converted to string + * and prefixed by $prefix and suffixed by $suffix. * @param string[] $array * @return string[] */ diff --git a/vendor/nette/utils/src/Utils/Callback.php b/vendor/nette/utils/src/Utils/Callback.php index 1c34ac9..303b4aa 100644 --- a/vendor/nette/utils/src/Utils/Callback.php +++ b/vendor/nette/utils/src/Utils/Callback.php @@ -8,7 +8,7 @@ namespace Nette\Utils; use Nette; -use function explode, func_get_args, ini_get, is_array, is_callable, is_object, is_string, preg_replace, restore_error_handler, set_error_handler, sprintf, str_contains, str_ends_with; +use function func_get_args, ini_get, is_array, is_object, is_string, sprintf; /** @@ -20,24 +20,21 @@ final class Callback /** * Invokes internal PHP function with own error handler. - * @param callable-string $function - * @param list<mixed> $args - * @param callable(string, int): (bool|void|null) $onError */ public static function invokeSafe(string $function, array $args, callable $onError): mixed { - $prev = set_error_handler(function (int $severity, string $message, string $file, int $line) use ($onError, &$prev, $function): bool { + $prev = set_error_handler(function ($severity, $message, $file) use ($onError, &$prev, $function): ?bool { if ($file === __FILE__) { $msg = ini_get('html_errors') ? Html::htmlToText($message) : $message; - $msg = (string) preg_replace("#^$function\\(.*?\\): #", '', $msg); + $msg = preg_replace("#^$function\\(.*?\\): #", '', $msg); if ($onError($msg, $severity) !== false) { - return true; + return null; } } - return $prev ? $prev(...func_get_args()) !== false : false; + return $prev ? $prev(...func_get_args()) : false; }); try { @@ -49,18 +46,18 @@ final class Callback /** - * Checks that $callable is a valid PHP callback and returns it. With $syntax set to true, only verifies - * the structural validity without checking whether the class or method actually exists. + * Checks that $callable is valid PHP callback. Otherwise throws exception. If the $syntax is set to true, only verifies + * that $callable has a valid structure to be used as a callback, but does not verify if the class or method actually exists. * @return callable * @throws Nette\InvalidArgumentException */ - public static function check(mixed $callable, bool $syntax = false): mixed + public static function check(mixed $callable, bool $syntax = false) { if (!is_callable($callable, $syntax)) { throw new Nette\InvalidArgumentException( $syntax - ? 'Given value is not a callable type.' - : sprintf("Callback '%s' is not callable.", self::toString($callable)), + ? 'Given value is not a callable type.' + : sprintf("Callback '%s' is not callable.", self::toString($callable)), ); } @@ -88,7 +85,7 @@ final class Callback * @param callable $callable type check is escalated to ReflectionException * @throws \ReflectionException if callback is not valid */ - public static function toReflection(mixed $callable): \ReflectionMethod|\ReflectionFunction + public static function toReflection($callable): \ReflectionMethod|\ReflectionFunction { if ($callable instanceof \Closure) { $callable = self::unwrap($callable); @@ -101,7 +98,6 @@ final class Callback } elseif (is_object($callable) && !$callable instanceof \Closure) { return new ReflectionMethod($callable, '__invoke'); } else { - assert($callable instanceof \Closure || is_string($callable)); return new \ReflectionFunction($callable); } } @@ -118,9 +114,8 @@ final class Callback /** * Unwraps closure created by Closure::fromCallable(). - * @return callable|array{object|class-string, string}|string */ - public static function unwrap(\Closure $closure): callable|array|string + public static function unwrap(\Closure $closure): callable|array { $r = new \ReflectionFunction($closure); $class = $r->getClosureScopeClass()?->name; diff --git a/vendor/nette/utils/src/Utils/DateTime.php b/vendor/nette/utils/src/Utils/DateTime.php index af4e94d..fce372e 100644 --- a/vendor/nette/utils/src/Utils/DateTime.php +++ b/vendor/nette/utils/src/Utils/DateTime.php @@ -7,14 +7,17 @@ namespace Nette\Utils; -use function array_merge, checkdate, implode, is_numeric, is_string, preg_replace_callback, sprintf, time, trim; +use Nette; +use function is_string; /** - * Extends PHP's DateTime with strict validation and additional factory methods. + * DateTime. */ class DateTime extends \DateTime implements \JsonSerializable { + use Nette\SmartObject; + /** minute in seconds */ public const MINUTE = 60; @@ -58,7 +61,7 @@ class DateTime extends \DateTime implements \JsonSerializable /** * Creates DateTime object. - * @throws \Exception if the date and time are not valid. + * @throws Nette\InvalidArgumentException if the date and time are not valid. */ public static function fromParts( int $year, @@ -69,10 +72,17 @@ class DateTime extends \DateTime implements \JsonSerializable float $second = 0.0, ): static { - $sec = (int) floor($second); - return (new static('')) - ->setDate($year, $month, $day) - ->setTime($hour, $minute, $sec, (int) round(($second - $sec) * 1e6)); + $s = sprintf('%04d-%02d-%02d %02d:%02d:%02.5F', $year, $month, $day, $hour, $minute, $second); + if ( + !checkdate($month, $day, $year) + || $hour < 0 || $hour > 23 + || $minute < 0 || $minute > 59 + || $second < 0 || $second >= 60 + ) { + throw new Nette\InvalidArgumentException("Invalid date '$s'"); + } + + return new static($s); } @@ -110,7 +120,7 @@ class DateTime extends \DateTime implements \JsonSerializable public function setDate(int $year, int $month, int $day): static { if (!checkdate($month, $day, $year)) { - throw new \Exception(sprintf('The date %04d-%02d-%02d is not valid.', $year, $month, $day)); + trigger_error(sprintf(self::class . ': The date %04d-%02d-%02d is not valid.', $year, $month, $day), E_USER_WARNING); } return parent::setDate($year, $month, $day); } @@ -124,7 +134,10 @@ class DateTime extends \DateTime implements \JsonSerializable || $second < 0 || $second >= 60 || $microsecond < 0 || $microsecond >= 1_000_000 ) { - throw new \Exception(sprintf('The time %02d:%02d:%08.5F is not valid.', $hour, $minute, $second + $microsecond / 1_000_000)); + trigger_error( + sprintf(self::class . ': The time %02d:%02d:%08.5F is not valid.', $hour, $minute, $second + $microsecond / 1_000_000), + E_USER_WARNING, + ); } return parent::setTime($hour, $minute, $second, $microsecond); } @@ -140,7 +153,7 @@ class DateTime extends \DateTime implements \JsonSerializable } - private function apply(string $datetime, ?\DateTimeZone $timezone = null, bool $ctr = false): void + private function apply(string $datetime, $timezone = null, bool $ctr = false): void { $relPart = ''; $absPart = preg_replace_callback( @@ -153,7 +166,7 @@ class DateTime extends \DateTime implements \JsonSerializable ); if ($ctr) { - parent::__construct($absPart, $timezone); + parent::__construct(trim($absPart), $timezone); $this->handleErrors($datetime); } elseif (trim($absPart)) { parent::modify($absPart) && $this->handleErrors($datetime); @@ -187,7 +200,7 @@ class DateTime extends \DateTime implements \JsonSerializable /** - * Returns a modified copy of the object. Use (clone $dt)->modify(...) for better type safety. + * You'd better use: (clone $dt)->modify(...) */ public function modifyClone(string $modify = ''): static { @@ -201,7 +214,7 @@ class DateTime extends \DateTime implements \JsonSerializable $errors = self::getLastErrors(); $errors = array_merge($errors['errors'] ?? [], $errors['warnings'] ?? []); if ($errors) { - throw new \Exception(implode(', ', $errors) . " '$value'"); + trigger_error(self::class . ': ' . implode(', ', $errors) . " '$value'", E_USER_WARNING); } } } diff --git a/vendor/nette/utils/src/Utils/DateTimeImmutable.php b/vendor/nette/utils/src/Utils/DateTimeImmutable.php deleted file mode 100644 index f4f9218..0000000 --- a/vendor/nette/utils/src/Utils/DateTimeImmutable.php +++ /dev/null @@ -1,187 +0,0 @@ -<?php declare(strict_types=1); - -/** - * This file is part of the Nette Framework (https://nette.org) - * Copyright (c) 2004 David Grudl (https://davidgrudl.com) - */ - -namespace Nette\Utils; - -use function array_merge, checkdate, implode, is_int, is_string, preg_match, preg_replace_callback, sprintf, trim; - - -/** - * Extends PHP's DateTimeImmutable with strict validation and additional factory methods. - * Invalid dates and times are rejected with an exception instead of being silently adjusted. - * All modifications return a new instance, the original object never changes. - */ -class DateTimeImmutable extends \DateTimeImmutable implements \JsonSerializable -{ - /** matches relative sub-day parts (minutes, seconds, ...) that must be applied in UTC to be DST-safe */ - private const RelativePattern = '/[+-]?\s*\d+\s+((microsecond|millisecond|[mµu]sec)s?|[mµ]s|sec(ond)?s?|min(ute)?s?|hours?)(\s+ago)?\b/iu'; - - - /** - * Creates a DateTimeImmutable object from a string, UNIX timestamp, or other DateTimeInterface object. - * @throws \Exception if the date and time are not valid. - */ - public static function from(string|int|\DateTimeInterface|null $time): static - { - if ($time instanceof \DateTimeInterface) { - return static::createFromInterface($time); - } elseif (is_int($time)) { - return (new static)->setTimestamp($time); - } else { // textual or null - return new static((string) $time); - } - } - - - /** - * Creates DateTimeImmutable object. - * @throws \Exception if the date and time are not valid. - */ - public static function fromParts( - int $year, - int $month, - int $day, - int $hour = 0, - int $minute = 0, - float $second = 0.0, - ): static - { - $sec = (int) floor($second); - return (new static) - ->setDate($year, $month, $day) - ->setTime($hour, $minute, $sec, (int) round(($second - $sec) * 1e6)); - } - - - /** - * Returns a new DateTimeImmutable object formatted according to the specified format. - */ - public static function createFromFormat( - string $format, - string $datetime, - string|\DateTimeZone|null $timezone = null, - ): static|false - { - if (is_string($timezone)) { - $timezone = new \DateTimeZone($timezone); - } - - $date = parent::createFromFormat($format, $datetime, $timezone); - return $date ? static::from($date) : false; - } - - - public function __construct(string $datetime = 'now', ?\DateTimeZone $timezone = null) - { - if (preg_match(self::RelativePattern, $datetime)) { - // sub-day relative parts must be applied in UTC, which cannot happen inside a constructor => resolve & re-parse - $result = self::resolve(null, $datetime, $timezone); - parent::__construct($result->format('Y-m-d H:i:s.u'), $result->getTimezone()); - } else { - parent::__construct($datetime, $timezone); - self::handleErrors($datetime); - } - } - - - public function modify(string $modifier): static - { - return static::createFromInterface(self::resolve($this, $modifier, null)); - } - - - public function setDate(int $year, int $month, int $day): static - { - if (!checkdate($month, $day, $year)) { - throw new \Exception(sprintf('The date %04d-%02d-%02d is not valid.', $year, $month, $day)); - } - return parent::setDate($year, $month, $day); - } - - - public function setTime(int $hour, int $minute, int $second = 0, int $microsecond = 0): static - { - if ( - $hour < 0 || $hour > 23 - || $minute < 0 || $minute > 59 - || $second < 0 || $second >= 60 - || $microsecond < 0 || $microsecond >= 1_000_000 - ) { - throw new \Exception(sprintf('The time %02d:%02d:%08.5F is not valid.', $hour, $minute, $second + $microsecond / 1_000_000)); - } - return parent::setTime($hour, $minute, $second, $microsecond); - } - - - /** - * Splits the input into absolute and relative parts and returns the resulting instant. Relative sub-day - * parts are applied in UTC so that crossing a DST boundary does not shift the result. - */ - private static function resolve(?\DateTimeInterface $base, string $input, ?\DateTimeZone $timezone): \DateTimeImmutable - { - $relPart = ''; - $absPart = preg_replace_callback( - self::RelativePattern, - function ($m) use (&$relPart) { - $relPart .= $m[0] . ' '; - return ''; - }, - $input, - ); - - if ($base === null) { - $result = new \DateTimeImmutable($absPart, $timezone); - self::handleErrors($input); - } else { - $result = \DateTimeImmutable::createFromInterface($base); - if (trim($absPart) !== '') { - $modified = @$result->modify($absPart); // @ - on PHP 8.2 an invalid modifier emits a warning and returns false instead of throwing; handleErrors() turns it into an exception - self::handleErrors($input); - $result = $modified ?: $result; - } - } - - if ($relPart !== '') { - $timezone ??= $result->getTimezone(); - $result = $result - ->setTimezone(new \DateTimeZone('UTC')) - ->modify($relPart) - ->setTimezone($timezone); - self::handleErrors($input); - } - - return $result; - } - - - /** - * Returns JSON representation in ISO 8601 (used by JavaScript). - */ - public function jsonSerialize(): string - { - return $this->format('c'); - } - - - /** - * Returns the date and time in the format 'Y-m-d H:i:s'. - */ - public function __toString(): string - { - return $this->format('Y-m-d H:i:s'); - } - - - private static function handleErrors(string $value): void - { - $errors = self::getLastErrors(); - $errors = array_merge($errors['errors'] ?? [], $errors['warnings'] ?? []); - if ($errors) { - throw new \Exception(implode(', ', $errors) . " '$value'"); - } - } -} diff --git a/vendor/nette/utils/src/Utils/FileInfo.php b/vendor/nette/utils/src/Utils/FileInfo.php index 64eeb74..a45c091 100644 --- a/vendor/nette/utils/src/Utils/FileInfo.php +++ b/vendor/nette/utils/src/Utils/FileInfo.php @@ -8,7 +8,6 @@ namespace Nette\Utils; use Nette; -use const DIRECTORY_SEPARATOR; /** @@ -19,10 +18,10 @@ final class FileInfo extends \SplFileInfo { public function __construct( string $file, - private readonly string $relativePath = '', + private string $relativePath = '', ) { parent::__construct($file); - $this->setInfoClass(self::class); + $this->setInfoClass(static::class); } diff --git a/vendor/nette/utils/src/Utils/FileSystem.php b/vendor/nette/utils/src/Utils/FileSystem.php index a665665..2de21e2 100644 --- a/vendor/nette/utils/src/Utils/FileSystem.php +++ b/vendor/nette/utils/src/Utils/FileSystem.php @@ -8,7 +8,7 @@ namespace Nette\Utils; use Nette; -use function array_pop, chmod, decoct, dirname, end, fclose, file_exists, file_get_contents, file_put_contents, fopen, implode, is_dir, is_file, is_link, mkdir, preg_match, preg_split, realpath, rename, rmdir, rtrim, sprintf, str_replace, stream_copy_to_stream, stream_is_local, strtr, uniqid, unlink, usleep; +use function sprintf; use const DIRECTORY_SEPARATOR; @@ -21,7 +21,7 @@ final class FileSystem * Creates a directory if it does not exist, including parent directories. * @throws Nette\IOException on error occurred */ - public static function createDir(string $dir, int $mode = 0o777): void + public static function createDir(string $dir, int $mode = 0777): void { if (!is_dir($dir) && !@mkdir($dir, $mode, recursive: true) && !is_dir($dir)) { // @ - dir may already exist throw new Nette\IOException(sprintf( @@ -50,11 +50,13 @@ final class FileSystem } elseif (is_dir($origin)) { static::createDir($target); foreach (new \FilesystemIterator($target) as $item) { - \assert($item instanceof \SplFileInfo); static::delete($item->getPathname()); } - foreach ($iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($origin, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST) as $item) { + foreach ($iterator = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($origin, \RecursiveDirectoryIterator::SKIP_DOTS), + \RecursiveIteratorIterator::SELF_FIRST, + ) as $item) { if ($item->isDir()) { static::createDir($target . '/' . $iterator->getSubPathname()); } else { @@ -111,7 +113,6 @@ final class FileSystem } } elseif (is_dir($path)) { foreach (new \FilesystemIterator($path) as $item) { - \assert($item instanceof \SplFileInfo); static::delete($item->getPathname()); } @@ -208,10 +209,10 @@ final class FileSystem /** - * Writes the string to a file. Creates the parent directory if it does not exist. Pass null as $mode to skip chmod. + * Writes the string to a file. * @throws Nette\IOException on error occurred */ - public static function write(string $file, string $content, ?int $mode = 0o666): void + public static function write(string $file, string $content, ?int $mode = 0666): void { static::createDir(dirname($file)); if (@file_put_contents($file, $content) === false) { // @ is escalated to exception @@ -233,42 +234,12 @@ final class FileSystem } - /** - * Writes the string to a file atomically: the content is written to a temporary file, which then replaces - * the target, so a concurrent reader never sees the file partially written or truncated. - * Creates the parent directory if it does not exist. Pass null as $mode to skip chmod. - * @throws Nette\IOException on error occurred - */ - public static function writeAtomic(string $file, string $content, ?int $mode = 0o666): void - { - $file = realpath($file) ?: $file; // writes through a symlink to its target, as write() does - $tmp = $file . '.' . uniqid('', more_entropy: true) . '.tmp'; - try { - static::write($tmp, $content, $mode); - // plain rename() is atomic; static::rename() must not be used here, it deletes the target first - for ($i = 0; !@rename($tmp, $file); $i++) { // @ is escalated to exception - if (!Helpers::IsWindows || $i >= 20) { - throw new Nette\IOException(sprintf( - "Unable to write file '%s'. %s", - self::normalizePath($file), - Helpers::getLastError(), - )); - } - usleep(5_000); // on Windows, rename fails while the target is open in another process - } - } catch (\Throwable $e) { - @unlink($tmp); - throw $e; - } - } - - /** * Sets file permissions to `$fileMode` or directory permissions to `$dirMode`. * Recursively traverses and sets permissions on the entire contents of the directory as well. * @throws Nette\IOException on error occurred */ - public static function makeWritable(string $path, int $dirMode = 0o777, int $fileMode = 0o666): void + public static function makeWritable(string $path, int $dirMode = 0777, int $fileMode = 0666): void { if (is_file($path)) { if (!@chmod($path, $fileMode)) { // @ is escalated to exception @@ -281,7 +252,6 @@ final class FileSystem } } elseif (is_dir($path)) { foreach (new \FilesystemIterator($path) as $item) { - \assert($item instanceof \SplFileInfo); static::makeWritable($item->getPathname(), $dirMode, $fileMode); } @@ -308,19 +278,6 @@ final class FileSystem } - /** - * Determines whether the string is a valid cross-platform filename without any path information. - */ - public static function isValidFilename(string $name): bool - { - [$stem] = explode('.', $name, 2); - return $name !== '' && $name !== '.' && $name !== '..' - && !preg_match('#[\x00-\x1F<>:"|?*\\\/]#', $name) // control and reserved characters - && !str_ends_with($name, '.') && !str_ends_with($name, ' ') // trailing dots/spaces - && !preg_match('#^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$#i', $stem); // Windows reserved device names - } - - /** * Normalizes `..` and `.` and directory separators in path. */ diff --git a/vendor/nette/utils/src/Utils/Finder.php b/vendor/nette/utils/src/Utils/Finder.php index 87e8e39..77265d9 100644 --- a/vendor/nette/utils/src/Utils/Finder.php +++ b/vendor/nette/utils/src/Utils/Finder.php @@ -8,12 +8,12 @@ namespace Nette\Utils; use Nette; -use function array_filter, array_merge, array_values, count, func_get_args, func_num_args, glob, implode, is_array, is_dir, iterator_to_array, preg_match, preg_quote, preg_replace, preg_split, rtrim, spl_object_id, sprintf, str_starts_with, strnatcmp, strpbrk, strrpos, strtolower, strtr, substr, trigger_error, usort; -use const DIRECTORY_SEPARATOR, E_USER_DEPRECATED, GLOB_NOESCAPE, GLOB_NOSORT, GLOB_ONLYDIR; +use function count, func_get_args, func_num_args, is_array, sprintf; +use const GLOB_NOESCAPE, GLOB_NOSORT, GLOB_ONLYDIR; /** - * Searches for files and directories in directory trees. + * Finder allows searching through directory trees using iterator. * * Finder::findFiles('*.php') * ->size('> 10kB') @@ -24,43 +24,42 @@ use const DIRECTORY_SEPARATOR, E_USER_DEPRECATED, GLOB_NOESCAPE, GLOB_NOSORT, GL */ class Finder implements \IteratorAggregate { + use Nette\SmartObject; + /** @var array<array{string, string}> */ private array $find = []; /** @var string[] */ private array $in = []; - /** @var array<\Closure(FileInfo): bool> */ + /** @var \Closure[] */ private array $filters = []; - /** @var array<\Closure(FileInfo): bool> */ + /** @var \Closure[] */ private array $descentFilters = []; /** @var array<string|self> */ private array $appends = []; private bool $childFirst = false; - /** @var ?(\Closure(FileInfo, FileInfo): int) */ - private ?\Closure $sort = null; + /** @var ?callable */ + private $sort; private int $maxDepth = -1; private bool $ignoreUnreadableDirs = true; /** - * Begins search for files and directories matching mask. The ** wildcard searches recursively; a trailing slash limits the mask to directories. - * @param string|list<string> $masks + * Begins search for files and directories matching mask. */ public static function find(string|array $masks = ['*']): static { $masks = is_array($masks) ? $masks : func_get_args(); // compatibility with variadic - $files = array_filter($masks, fn(string $mask): bool => !self::hasTrailingSeparator($mask)); // trailing slash means directories only - return (new static)->addMask($masks, 'dir')->addMask(array_values($files), 'file'); + return (new static)->addMask($masks, 'dir')->addMask($masks, 'file'); } /** - * Begins search for files matching mask. The ** wildcard searches recursively. - * @param string|list<string> $masks + * Begins search for files matching mask. */ public static function findFiles(string|array $masks = ['*']): static { @@ -70,8 +69,7 @@ class Finder implements \IteratorAggregate /** - * Begins search for directories matching mask. The ** wildcard searches recursively. - * @param string|list<string> $masks + * Begins search for directories matching mask. */ public static function findDirectories(string|array $masks = ['*']): static { @@ -82,7 +80,6 @@ class Finder implements \IteratorAggregate /** * Finds files matching the specified masks. - * @param string|list<string> $masks */ public function files(string|array $masks = ['*']): static { @@ -92,7 +89,6 @@ class Finder implements \IteratorAggregate /** * Finds directories matching the specified masks. - * @param string|list<string> $masks */ public function directories(string|array $masks = ['*']): static { @@ -100,39 +96,27 @@ class Finder implements \IteratorAggregate } - /** @param list<string> $masks */ private function addMask(array $masks, string $mode): static { foreach ($masks as $mask) { - $orig = $mask; + $mask = FileSystem::unixSlashes($mask); if ($mode === 'dir') { - $mask = rtrim($mask, '/\\'); + $mask = rtrim($mask, '/'); } - if ($mask === '' || ($mode === 'file' && self::hasTrailingSeparator($mask))) { - throw new Nette\InvalidArgumentException("Invalid mask '$orig'"); + if ($mask === '' || ($mode === 'file' && str_ends_with($mask, '/'))) { + throw new Nette\InvalidArgumentException("Invalid mask '$mask'"); } - $this->find[] = [self::expandGlobStar($mask), $mode]; + if (str_starts_with($mask, '**/')) { + $mask = substr($mask, 3); + } + $this->find[] = [$mask, $mode]; } return $this; } - private static function hasTrailingSeparator(string $mask): bool - { - return ($last = substr($mask, -1)) === '/' || $last === '\\'; - } - - - // Expands a ** that is not followed by a slash into **/*, so that e.g. "test/**" and "**.c" search recursively. - private static function expandGlobStar(string $mask): string - { - return preg_replace('~(?<=^|[/\\\])\*\*(?![/\\\])~', '**/*', $mask); - } - - /** - * Searches in the given directories. Wildcards * and ? are allowed; unlike in masks, [ and ] are taken literally. - * @param string|list<string> $paths + * Searches in the given directories. Wildcards are allowed. */ public function in(string|array $paths): static { @@ -143,25 +127,23 @@ class Finder implements \IteratorAggregate /** - * Searches recursively from the given directories. Wildcards * and ? are allowed; unlike in masks, [ and ] are taken literally. - * @param string|list<string> $paths + * Searches recursively from the given directories. Wildcards are allowed. */ public function from(string|array $paths): static { $paths = is_array($paths) ? $paths : func_get_args(); // compatibility with variadic - $this->addLocation($paths, DIRECTORY_SEPARATOR . '**'); + $this->addLocation($paths, '/**'); return $this; } - /** @param list<string> $paths */ private function addLocation(array $paths, string $ext): void { foreach ($paths as $path) { if ($path === '') { throw new Nette\InvalidArgumentException("Invalid directory '$path'"); } - $path = rtrim($path, '/\\'); + $path = rtrim(FileSystem::unixSlashes($path), '/'); $this->in[] = $path . $ext; } } @@ -188,12 +170,12 @@ class Finder implements \IteratorAggregate /** - * Sets a comparison function for sorting entries within each directory. + * Set a compare function for sorting directory entries. The function will be called to sort entries from the same directory. * @param callable(FileInfo, FileInfo): int $callback */ public function sortBy(callable $callback): static { - $this->sort = $callback(...); + $this->sort = $callback; return $this; } @@ -209,8 +191,7 @@ class Finder implements \IteratorAggregate /** - * Appends the specified file paths to results. Passing null creates and returns a new sub-finder whose results are appended. - * @param string|list<string>|null $paths + * Adds the specified paths or appends a new finder that returns. */ public function append(string|array|null $paths = null): static { @@ -227,29 +208,23 @@ class Finder implements \IteratorAggregate /** - * Skips entries that match the given masks, using the same grammar as find() masks, relative to the directories from in() or from(). - * A trailing slash excludes directories only; a trailing /* or /** excludes the contents while keeping the directory itself. - * @param string|list<string> $masks + * Skips entries that matches the given masks relative to the ones defined with the in() or from() methods. */ public function exclude(string|array $masks): static { $masks = is_array($masks) ? $masks : func_get_args(); // compatibility with variadic foreach ($masks as $mask) { - $orig = $mask; $mask = FileSystem::unixSlashes($mask); - if (FileSystem::isAbsolute($mask) || $mask === '..' || str_starts_with($mask, '../')) { - trigger_error("Absolute or ../ mask '$orig' in exclude() is deprecated and will change meaning, use a mask relative to the searched directory.", E_USER_DEPRECATED); - } - if (!preg_match('~^/?(\*\*/)?(.+?)(/\*\*|/\*|/|)$~D', $mask, $m)) { - throw new Nette\InvalidArgumentException("Invalid mask '$orig'"); + if (!preg_match('~^/?(\*\*/)?(.+)(/\*\*|/\*|/|)$~D', $mask, $m)) { + throw new Nette\InvalidArgumentException("Invalid mask '$mask'"); } $end = $m[3]; - $re = $this->buildPattern(self::expandGlobStar($m[2])); + $re = $this->buildPattern($m[2]); $filter = fn(FileInfo $file): bool => ($end && !$file->isDir()) || !preg_match($re, FileSystem::unixSlashes($file->getRelativePathname())); $this->descentFilter($filter); - if ($end === '' || $end === '/') { + if ($end !== '/*') { $this->filter($filter); } } @@ -264,7 +239,7 @@ class Finder implements \IteratorAggregate */ public function filter(callable $callback): static { - $this->filters[] = $callback(...); + $this->filters[] = \Closure::fromCallable($callback); return $this; } @@ -275,7 +250,7 @@ class Finder implements \IteratorAggregate */ public function descentFilter(callable $callback): static { - $this->descentFilters[] = $callback(...); + $this->descentFilters[] = \Closure::fromCallable($callback); return $this; } @@ -292,7 +267,6 @@ class Finder implements \IteratorAggregate /** * Restricts the search by size. $operator accepts "[operator] [size] [unit]" example: >=10kB - * @param '>'|'>='|'<'|'<='|'='|'=='|'==='|'!='|'!=='|'<>' $operator or predicate string */ public function size(string $operator, ?int $size = null): static { @@ -303,7 +277,7 @@ class Finder implements \IteratorAggregate [, $operator, $size, $unit] = $matches; $units = ['' => 1, 'k' => 1e3, 'm' => 1e6, 'g' => 1e9]; - $size = (float) $size * $units[strtolower($unit)]; + $size *= $units[strtolower($unit)]; $operator = $operator ?: '='; } @@ -313,7 +287,6 @@ class Finder implements \IteratorAggregate /** * Restricts the search by modified time. $operator accepts "[operator] [date]" example: >1978-01-23 - * @param '>'|'>='|'<'|'<='|'='|'=='|'==='|'!='|'!=='|'<>' $operator or predicate string */ public function date(string $operator, string|int|\DateTimeInterface|null $date = null): static { @@ -356,6 +329,7 @@ class Finder implements \IteratorAggregate if ($item instanceof self) { yield from $item->getIterator(); } else { + $item = FileSystem::platformSlashes($item); yield $item => new FileInfo($item); } } @@ -376,7 +350,13 @@ class Finder implements \IteratorAggregate } try { - $pathNames = new \FilesystemIterator($dir, \FilesystemIterator::FOLLOW_SYMLINKS | \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::CURRENT_AS_PATHNAME); + $pathNames = new \FilesystemIterator( + $dir, + \FilesystemIterator::FOLLOW_SYMLINKS + | \FilesystemIterator::SKIP_DOTS + | \FilesystemIterator::CURRENT_AS_PATHNAME + | \FilesystemIterator::UNIX_PATHS, + ); } catch (\UnexpectedValueException $e) { if ($this->ignoreUnreadableDirs) { return; @@ -385,7 +365,7 @@ class Finder implements \IteratorAggregate } } - $files = $this->convertToFiles($pathNames, implode(DIRECTORY_SEPARATOR, $subdirs), FileSystem::isAbsolute($dir)); + $files = $this->convertToFiles($pathNames, implode('/', $subdirs), FileSystem::isAbsolute($dir)); if ($this->sort) { $files = iterator_to_array($files); @@ -427,22 +407,18 @@ class Finder implements \IteratorAggregate } - /** @param iterable<string> $pathNames */ private function convertToFiles(iterable $pathNames, string $relativePath, bool $absolute): \Generator { foreach ($pathNames as $pathName) { if (!$absolute) { - $pathName = preg_replace('~\.?[\\\/]~A', '', $pathName); + $pathName = preg_replace('~\.?/~A', '', $pathName); } + $pathName = FileSystem::platformSlashes($pathName); yield new FileInfo($pathName, $relativePath); } } - /** - * @param (\Closure(FileInfo): bool)[] $filters - * @param array<int, bool> $cache - */ private function proveFilters(array $filters, FileInfo $file, array &$cache): bool { foreach ($filters as $filter) { @@ -471,7 +447,7 @@ class Finder implements \IteratorAggregate } else { foreach ($this->in ?: ['.'] as $in) { $in = strtr($in, ['[' => '[[]', ']' => '[]]']); // in path, do not treat [ and ] as a pattern by glob() - $splits[] = self::splitRecursivePart($in . DIRECTORY_SEPARATOR . $mask); + $splits[] = self::splitRecursivePart($in . '/' . $mask); } } @@ -498,17 +474,14 @@ class Finder implements \IteratorAggregate /** * Since glob() does not know ** wildcard, we divide the path into a part for glob and a part for manual traversal. - * @return array{string, string, bool} */ private static function splitRecursivePart(string $path): array { - $pos = strrpos(strtr($path, '\\', '/'), '/'); - $dir = $pos === false ? '' : substr($path, 0, $pos + 1); - $file = $pos === false ? $path : substr($path, $pos + 1); - $parts = preg_split('~(?<=^|[\\\/])\*\*($|[\\\/])~', $dir, 2); + $a = strrpos($path, '/'); + $parts = preg_split('~(?<=^|/)\*\*($|/)~', substr($path, 0, $a + 1), 2); return isset($parts[1]) - ? [$parts[0], $parts[1] . $file, true] - : [$parts[0], $file, false]; + ? [$parts[0], $parts[1] . substr($path, $a + 1), true] + : [$parts[0], substr($path, $a + 1), false]; } @@ -517,7 +490,6 @@ class Finder implements \IteratorAggregate */ private function buildPattern(string $mask): string { - $mask = FileSystem::unixSlashes($mask); if ($mask === '*') { return '##'; } elseif (str_starts_with($mask, './')) { diff --git a/vendor/nette/utils/src/Utils/Floats.php b/vendor/nette/utils/src/Utils/Floats.php index 02cebeb..4c8fbe2 100644 --- a/vendor/nette/utils/src/Utils/Floats.php +++ b/vendor/nette/utils/src/Utils/Floats.php @@ -8,7 +8,6 @@ namespace Nette\Utils; use Nette; -use function abs, is_finite, is_nan, max, round; /** diff --git a/vendor/nette/utils/src/Utils/Helpers.php b/vendor/nette/utils/src/Utils/Helpers.php index 73d77bb..ab29008 100644 --- a/vendor/nette/utils/src/Utils/Helpers.php +++ b/vendor/nette/utils/src/Utils/Helpers.php @@ -8,13 +8,10 @@ namespace Nette\Utils; use Nette; -use function array_unique, ini_get, levenshtein, max, min, ob_end_clean, ob_get_clean, ob_start, preg_replace, strlen; +use function ini_get, strlen; use const PHP_OS_FAMILY; -/** - * Miscellaneous utilities. - */ class Helpers { public const IsWindows = PHP_OS_FAMILY === 'Windows'; @@ -22,7 +19,6 @@ class Helpers /** * Executes a callback and returns the captured output as a string. - * @param callable(): void $func */ public static function capture(callable $func): string { @@ -39,7 +35,7 @@ class Helpers /** * Returns the last occurred PHP error or an empty string if no error occurred. Unlike error_get_last(), - * it is not affected by the PHP directive html_errors and always returns text, not HTML. + * it is nit affected by the PHP directive html_errors and always returns text, not HTML. */ public static function getLastError(): string { @@ -61,7 +57,6 @@ class Helpers /** * Returns value clamped to the inclusive range of min and max. - * @return ($value is float ? float : ($min is float ? float : ($max is float ? float : int))) */ public static function clamp(int|float $value, int|float $min, int|float $max): int|float { @@ -74,7 +69,7 @@ class Helpers /** - * Finds the string from $possibilities most similar to $value using Levenshtein distance, or null if none is close enough. + * Looks for a string from possibilities that is most similar to value, but not the same (for 8-bit encoding). * @param string[] $possibilities */ public static function getSuggestion(array $possibilities, string $value): ?string @@ -94,7 +89,6 @@ class Helpers /** * Compares two values in the same way that PHP does. Recognizes operators: >, >=, <, <=, =, ==, ===, !=, !==, <> - * @param '>'|'>='|'<'|'<='|'='|'=='|'==='|'!='|'!=='|'<>' $operator */ public static function compare(mixed $left, string $operator, mixed $right): bool { @@ -103,9 +97,9 @@ class Helpers '>=' => $left >= $right, '<' => $left < $right, '<=' => $left <= $right, - '=', '==' => $left == $right, + '=', '==' => $left == $right, // intentionally == '===' => $left === $right, - '!=', '<>' => $left != $right, + '!=', '<>' => $left != $right, // intentionally != '!==' => $left !== $right, default => throw new Nette\InvalidArgumentException("Unknown operator '$operator'"), }; diff --git a/vendor/nette/utils/src/Utils/Html.php b/vendor/nette/utils/src/Utils/Html.php index 437e39e..c3115c6 100644 --- a/vendor/nette/utils/src/Utils/Html.php +++ b/vendor/nette/utils/src/Utils/Html.php @@ -7,121 +7,122 @@ namespace Nette\Utils; +use Nette; use Nette\HtmlStringable; -use function array_merge, array_splice, count, explode, func_num_args, html_entity_decode, htmlspecialchars, http_build_query, implode, is_array, is_bool, is_float, is_object, is_string, json_encode, max, number_format, rtrim, str_contains, str_repeat, str_replace, strip_tags, strncmp, strpbrk, substr, trigger_error, ucfirst; -use const E_USER_DEPRECATED, ENT_HTML5, ENT_NOQUOTES, ENT_QUOTES; +use function count, func_num_args, is_array, is_bool, is_float, is_object, is_string; +use const ENT_HTML5, ENT_QUOTES; /** - * Generates HTML elements with automatic attribute escaping. + * HTML helper. * - * @property ?string $accept - * @property ?string $accesskey - * @property ?string $action - * @property ?string $align - * @property ?string $allow - * @property ?string $alt - * @property ?bool $async - * @property ?string $autocapitalize - * @property ?string $autocomplete - * @property ?bool $autofocus - * @property ?bool $autoplay - * @property ?string $charset - * @property ?bool $checked - * @property ?string $cite - * @property ?string $class - * @property ?int $cols - * @property ?int $colspan - * @property ?string $content - * @property ?bool $contenteditable - * @property ?bool $controls - * @property ?string $coords - * @property ?string $crossorigin - * @property ?string $data - * @property ?string $datetime - * @property ?string $decoding - * @property ?bool $default - * @property ?bool $defer - * @property ?string $dir - * @property ?string $dirname - * @property ?bool $disabled - * @property ?bool $download - * @property ?string $draggable - * @property ?string $dropzone - * @property ?string $enctype - * @property ?string $for - * @property ?string $form - * @property ?string $formaction - * @property ?string $formenctype - * @property ?string $formmethod - * @property ?bool $formnovalidate - * @property ?string $formtarget - * @property ?string $headers - * @property ?int $height - * @property ?bool $hidden - * @property ?float $high - * @property ?string $href - * @property ?string $hreflang - * @property ?string $id - * @property ?string $integrity - * @property ?string $inputmode - * @property ?bool $ismap - * @property ?string $itemprop - * @property ?string $kind - * @property ?string $label - * @property ?string $lang - * @property ?string $list - * @property ?bool $loop - * @property ?float $low - * @property ?float $max - * @property ?int $maxlength - * @property ?int $minlength - * @property ?string $media - * @property ?string $method - * @property ?float $min - * @property ?bool $multiple - * @property ?bool $muted - * @property ?string $name - * @property ?bool $novalidate - * @property ?bool $open - * @property ?float $optimum - * @property ?string $pattern - * @property ?string $ping - * @property ?string $placeholder - * @property ?string $poster - * @property ?string $preload - * @property ?string $radiogroup - * @property ?bool $readonly - * @property ?string $rel - * @property ?bool $required - * @property ?bool $reversed - * @property ?int $rows - * @property ?int $rowspan - * @property ?string $sandbox - * @property ?string $scope - * @property ?bool $selected - * @property ?string $shape - * @property ?int $size - * @property ?string $sizes - * @property ?string $slot - * @property ?int $span - * @property ?string $spellcheck - * @property ?string $src - * @property ?string $srcdoc - * @property ?string $srclang - * @property ?string $srcset - * @property ?int $start - * @property ?float $step - * @property ?string $style - * @property ?int $tabindex - * @property ?string $target - * @property ?string $title - * @property ?string $translate - * @property ?string $type - * @property ?string $usemap - * @property ?string $value - * @property ?int $width - * @property ?string $wrap + * @property string|null $accept + * @property string|null $accesskey + * @property string|null $action + * @property string|null $align + * @property string|null $allow + * @property string|null $alt + * @property bool|null $async + * @property string|null $autocapitalize + * @property string|null $autocomplete + * @property bool|null $autofocus + * @property bool|null $autoplay + * @property string|null $charset + * @property bool|null $checked + * @property string|null $cite + * @property string|null $class + * @property int|null $cols + * @property int|null $colspan + * @property string|null $content + * @property bool|null $contenteditable + * @property bool|null $controls + * @property string|null $coords + * @property string|null $crossorigin + * @property string|null $data + * @property string|null $datetime + * @property string|null $decoding + * @property bool|null $default + * @property bool|null $defer + * @property string|null $dir + * @property string|null $dirname + * @property bool|null $disabled + * @property bool|null $download + * @property string|null $draggable + * @property string|null $dropzone + * @property string|null $enctype + * @property string|null $for + * @property string|null $form + * @property string|null $formaction + * @property string|null $formenctype + * @property string|null $formmethod + * @property bool|null $formnovalidate + * @property string|null $formtarget + * @property string|null $headers + * @property int|null $height + * @property bool|null $hidden + * @property float|null $high + * @property string|null $href + * @property string|null $hreflang + * @property string|null $id + * @property string|null $integrity + * @property string|null $inputmode + * @property bool|null $ismap + * @property string|null $itemprop + * @property string|null $kind + * @property string|null $label + * @property string|null $lang + * @property string|null $list + * @property bool|null $loop + * @property float|null $low + * @property float|null $max + * @property int|null $maxlength + * @property int|null $minlength + * @property string|null $media + * @property string|null $method + * @property float|null $min + * @property bool|null $multiple + * @property bool|null $muted + * @property string|null $name + * @property bool|null $novalidate + * @property bool|null $open + * @property float|null $optimum + * @property string|null $pattern + * @property string|null $ping + * @property string|null $placeholder + * @property string|null $poster + * @property string|null $preload + * @property string|null $radiogroup + * @property bool|null $readonly + * @property string|null $rel + * @property bool|null $required + * @property bool|null $reversed + * @property int|null $rows + * @property int|null $rowspan + * @property string|null $sandbox + * @property string|null $scope + * @property bool|null $selected + * @property string|null $shape + * @property int|null $size + * @property string|null $sizes + * @property string|null $slot + * @property int|null $span + * @property string|null $spellcheck + * @property string|null $src + * @property string|null $srcdoc + * @property string|null $srclang + * @property string|null $srcset + * @property int|null $start + * @property float|null $step + * @property string|null $style + * @property int|null $tabindex + * @property string|null $target + * @property string|null $title + * @property string|null $translate + * @property string|null $type + * @property string|null $usemap + * @property string|null $value + * @property int|null $width + * @property string|null $wrap * * @method self accept(?string $val) * @method self accesskey(?string $val, bool $state = null) @@ -228,27 +229,23 @@ use const E_USER_DEPRECATED, ENT_HTML5, ENT_NOQUOTES, ENT_QUOTES; * @method self value(?string $val) * @method self width(?int $val) * @method self wrap(?string $val) - * - * @method static static text(mixed $text) - * @method static static html(mixed $html) - * - * @implements \IteratorAggregate<int, self|string> - * @implements \ArrayAccess<int, self|string> */ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringable { - /** @var array<string, mixed> element's attributes */ - public array $attrs = []; + use Nette\SmartObject; - /** @var array<string, int> void elements */ - public static array $emptyElements = [ + /** @var array<string, mixed> element's attributes */ + public $attrs = []; + + /** void elements */ + public static $emptyElements = [ 'img' => 1, 'hr' => 1, 'br' => 1, 'input' => 1, 'meta' => 1, 'area' => 1, 'embed' => 1, 'keygen' => 1, 'source' => 1, 'base' => 1, 'col' => 1, 'link' => 1, 'param' => 1, 'basefont' => 1, 'frame' => 1, 'isindex' => 1, 'wbr' => 1, 'command' => 1, 'track' => 1, ]; - /** @var array<int, self|string> nodes */ - protected array $children = []; + /** @var array<int, HtmlStringable|string> nodes */ + protected $children = []; /** element's name */ private string $name = ''; @@ -258,7 +255,7 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringab /** * Constructs new HTML element. - * @param array<string, mixed>|string|null $attrs element's attributes or plain text content + * @param array|string $attrs element's attributes or plain text content */ public static function el(?string $name = null, array|string|null $attrs = null): static { @@ -283,19 +280,8 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringab } - /** - * Creates a nameless element (fragment) containing the given children. - * Everything except HtmlStringable is escaped; use Html::html() for raw HTML. Nulls are skipped. - */ - public static function fragment(HtmlStringable|\Stringable|string|int|null ...$children): static - { - return (new static)->add(...$children); - } - - /** * Returns an object representing HTML text. - * @deprecated use Html::html() */ public static function fromHtml(string $html): static { @@ -305,7 +291,6 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringab /** * Returns an object representing plain text. - * @deprecated use Html::text() */ public static function fromText(string $text): static { @@ -361,7 +346,7 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringab /** - * Checks whether the element is a void (self-closing) element. + * Is element empty? */ final public function isEmpty(): bool { @@ -371,7 +356,6 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringab /** * Sets multiple attributes. - * @param array<string, mixed> $attrs */ public function addAttributes(array $attrs): static { @@ -434,7 +418,6 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringab /** * Unsets element's attributes. - * @param list<string> $attributes */ public function removeAttributes(array $attributes): static { @@ -447,7 +430,7 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringab /** - * Sets element's attribute via property assignment. + * Overloaded setter for element's attribute. */ final public function __set(string $name, mixed $value): void { @@ -456,7 +439,7 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringab /** - * Returns element's attribute via property access. + * Overloaded getter for element's attribute. */ final public function &__get(string $name): mixed { @@ -465,7 +448,7 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringab /** - * Checks if element's attribute is set. + * Overloaded tester for element's attribute. */ final public function __isset(string $name): bool { @@ -474,7 +457,7 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringab /** - * Unsets element's attribute via property unset. + * Overloaded unsetter for element's attribute. */ final public function __unset(string $name): void { @@ -483,15 +466,10 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringab /** - * Sets or returns element's attribute via method call. - * @param mixed[] $args + * Overloaded setter for element's attribute. */ final public function __call(string $m, array $args): mixed { - if ($m === 'text' || $m === 'html') { - trigger_error("Method \$el->$m() is deprecated, use set" . ucfirst($m) . "() for content or setAttribute() for the '$m' attribute; Html::$m() is a static factory.", E_USER_DEPRECATED); - } - $p = substr($m, 0, 3); if ($p === 'get' || $p === 'set' || $p === 'add') { $m = substr($m, 3); @@ -517,23 +495,8 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringab } - /** - * Creates element with escaped text (Html::text()) or raw HTML (Html::html()) content. - * @param mixed[] $args - */ - final public static function __callStatic(string $name, array $args): static - { - return match ($name) { - 'text' => (new static)->setText(...$args), - 'html' => (new static)->setHtml(...$args), - default => ObjectHelpers::strictStaticCall(static::class, $name), - }; - } - - /** * Special setter for element's attribute. - * @param array<string, mixed> $query */ final public function href(string $path, array $query = []): static { @@ -608,25 +571,10 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringab } - /** - * Appends the given children. Everything except HtmlStringable is escaped; use Html::html() for raw HTML. Nulls are skipped. - */ - public function add(HtmlStringable|\Stringable|string|int|null ...$children): static - { - foreach ($children as $child) { - if ($child !== null) { - $this->addText($child); - } - } - - return $this; - } - - /** * Adds new element's child. */ - final public function addHtml(HtmlStringable|string $child): static + final public function addHtml(mixed $child): static { return $this->insert(null, $child); } @@ -635,7 +583,7 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringab /** * Appends plain-text string to element content. */ - public function addText(\Stringable|string|int|null $text): static + public function addText(mixed $text): static { if (!$text instanceof HtmlStringable) { $text = htmlspecialchars((string) $text, ENT_NOQUOTES, 'UTF-8'); @@ -647,7 +595,6 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringab /** * Creates and adds a new Html child. - * @param array<string, mixed>|string|null $attrs */ final public function create(string $name, array|string|null $attrs = null): static { @@ -675,7 +622,7 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringab /** * Inserts (replaces) child node (\ArrayAccess implementation). - * @param ?int $index position or null for appending + * @param int|null $index position or null for appending * @param Html|string $child Html node or raw HTML string */ final public function offsetSet($index, $child): void @@ -688,7 +635,7 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringab * Returns child node (\ArrayAccess implementation). * @param int $index */ - final public function offsetGet($index): self|string + final public function offsetGet($index): HtmlStringable|string { return $this->children[$index]; } @@ -736,7 +683,7 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringab /** * Iterates over elements. - * @return \ArrayIterator<int, self|string> + * @return \ArrayIterator<int, HtmlStringable|string> */ final public function getIterator(): \ArrayIterator { @@ -746,7 +693,6 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringab /** * Returns all children. - * @return array<int, self|string> */ final public function getChildren(): array { @@ -755,7 +701,7 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringab /** - * Renders element's start tag, content and end tag. Pass indent level to enable pretty-printing. + * Renders element's start tag, content and end tag. */ final public function render(?int $indent = null): string { @@ -819,6 +765,10 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringab */ final public function attributes(): string { + if (!is_array($this->attrs)) { + return ''; + } + $s = ''; $attrs = $this->attrs; foreach ($attrs as $key => $value) { @@ -861,8 +811,8 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringab $q = str_contains($value, '"') ? "'" : '"'; $s .= ' ' . $key . '=' . $q . str_replace( - ['&', $q], - ['&', $q === '"' ? '"' : '''], + ['&', $q, '<'], + ['&', $q === '"' ? '"' : ''', '<'], $value, ) . (str_contains($value, '`') && strpbrk($value, ' <>"\'') === false ? ' ' : '') diff --git a/vendor/nette/utils/src/Utils/Image.php b/vendor/nette/utils/src/Utils/Image.php index 55d8026..c504c39 100644 --- a/vendor/nette/utils/src/Utils/Image.php +++ b/vendor/nette/utils/src/Utils/Image.php @@ -8,8 +8,7 @@ namespace Nette\Utils; use Nette; -use function is_array, is_int, is_string; -use const IMG_BMP, IMG_FLIP_BOTH, IMG_FLIP_HORIZONTAL, IMG_FLIP_VERTICAL, IMG_GIF, IMG_JPG, IMG_PNG, IMG_WEBP, PATHINFO_EXTENSION; +use function extension_loaded, is_array, is_int, is_string; /** @@ -22,7 +21,7 @@ use const IMG_BMP, IMG_FLIP_BOTH, IMG_FLIP_HORIZONTAL, IMG_FLIP_VERTICAL, IMG_GI * $image->send(); * </code> * - * @method Image affine(array<int, float|int> $affine, ?array{x: int, y: int, width: int, height: int} $clip = null) + * @method Image affine(array $affine, ?array $clip = null) * @method void alphaBlending(bool $enable) * @method void antialias(bool $enable) * @method void arc(int $centerX, int $centerY, int $width, int $height, int $startAngle, int $endAngle, ImageColor $color) @@ -39,51 +38,51 @@ use const IMG_BMP, IMG_FLIP_BOTH, IMG_FLIP_HORIZONTAL, IMG_FLIP_VERTICAL, IMG_GI * @method int colorResolve(int $red, int $green, int $blue) * @method int colorResolveAlpha(int $red, int $green, int $blue, int $alpha) * @method void colorSet(int $index, int $red, int $green, int $blue, int $alpha = 0) - * @method array{red: int, green: int, blue: int, alpha: int} colorsForIndex(int $color) + * @method array colorsForIndex(int $color) * @method int colorsTotal() * @method int colorTransparent(?int $color = null) - * @method void convolution(array<int, array<int, float>> $matrix, float $div, float $offset) + * @method void convolution(array $matrix, float $div, float $offset) * @method void copy(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH) * @method void copyMerge(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH, int $pct) * @method void copyMergeGray(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH, int $pct) * @method void copyResampled(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $dstW, int $dstH, int $srcW, int $srcH) * @method void copyResized(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $dstW, int $dstH, int $srcW, int $srcH) - * @method Image cropAuto(int $mode = 0, float $threshold = .5, ?ImageColor $color = null) + * @method Image cropAuto(int $mode = IMG_CROP_DEFAULT, float $threshold = .5, ?ImageColor $color = null) * @method void ellipse(int $centerX, int $centerY, int $width, int $height, ImageColor $color) * @method void fill(int $x, int $y, ImageColor $color) * @method void filledArc(int $centerX, int $centerY, int $width, int $height, int $startAngle, int $endAngle, ImageColor $color, int $style) * @method void filledEllipse(int $centerX, int $centerY, int $width, int $height, ImageColor $color) - * @method void filledPolygon(array<int, int> $points, ImageColor $color) + * @method void filledPolygon(array $points, ImageColor $color) * @method void filledRectangle(int $x1, int $y1, int $x2, int $y2, ImageColor $color) * @method void fillToBorder(int $x, int $y, ImageColor $borderColor, ImageColor $color) * @method void filter(int $filter, ...$args) * @method void flip(int $mode) - * @method array<int, int> ftText(float $size, float $angle, int $x, int $y, ImageColor $color, string $fontFile, string $text, array<string, mixed> $options = []) + * @method array ftText(float $size, float $angle, int $x, int $y, ImageColor $color, string $fontFile, string $text, array $options = []) * @method void gammaCorrect(float $inputgamma, float $outputgamma) - * @method array{int, int, int, int} getClip() + * @method array getClip() * @method int getInterpolation() * @method int interlace(?bool $enable = null) * @method bool isTrueColor() * @method void layerEffect(int $effect) * @method void line(int $x1, int $y1, int $x2, int $y2, ImageColor $color) - * @method void openPolygon(array<int, int> $points, ImageColor $color) + * @method void openPolygon(array $points, ImageColor $color) * @method void paletteCopy(Image $source) * @method void paletteToTrueColor() - * @method void polygon(array<int, int> $points, ImageColor $color) + * @method void polygon(array $points, ImageColor $color) * @method void rectangle(int $x1, int $y1, int $x2, int $y2, ImageColor $color) * @method mixed resolution(?int $resolutionX = null, ?int $resolutionY = null) * @method Image rotate(float $angle, ImageColor $backgroundColor) * @method void saveAlpha(bool $enable) - * @method Image scale(int $newWidth, int $newHeight = -1, int $mode = 3) + * @method Image scale(int $newWidth, int $newHeight = -1, int $mode = IMG_BILINEAR_FIXED) * @method void setBrush(Image $brush) * @method void setClip(int $x1, int $y1, int $x2, int $y2) - * @method void setInterpolation(int $method = 3) + * @method void setInterpolation(int $method = IMG_BILINEAR_FIXED) * @method void setPixel(int $x, int $y, ImageColor $color) - * @method void setStyle(array<int, int> $style) + * @method void setStyle(array $style) * @method void setThickness(int $thickness) * @method void setTile(Image $tile) * @method void trueColorToPalette(bool $dither, int $ncolors) - * @method array<int, int> ttfText(float $size, float $angle, int $x, int $y, ImageColor $color, string $fontfile, string $text, array<string, mixed> $options = []) + * @method array ttfText(float $size, float $angle, int $x, int $y, ImageColor $color, string $fontfile, string $text, array $options = []) * @property-read positive-int $width * @property-read positive-int $height * @property-read \GdImage $imageResource @@ -136,8 +135,14 @@ class Image public const EmptyGIF = "GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;"; - private const Formats = [ImageType::JPEG => 'jpeg', ImageType::PNG => 'png', ImageType::GIF => 'gif', ImageType::WEBP => 'webp', ImageType::AVIF => 'avif', ImageType::BMP => 'bmp']; - private const Sentinel = "\0"; + private const Formats = [ + ImageType::JPEG => 'jpeg', + ImageType::PNG => 'png', + ImageType::GIF => 'gif', + ImageType::WEBP => 'webp', + ImageType::AVIF => 'avif', + ImageType::BMP => 'bmp', + ]; private \GdImage $image; @@ -145,7 +150,6 @@ class Image /** * Returns RGB color (0..255) and transparency (0..127). * @deprecated use ImageColor::rgb() - * @return array{red: int, green: int, blue: int, alpha: int} */ public static function rgb(int $red, int $green, int $blue, int $transparency = 0): array { @@ -159,13 +163,11 @@ class Image /** - * Reads an image from a file and returns its type in $type. If $warnings is passed, recoverable decoder - * warnings are returned in it instead of being raised as a PHP warning. - * @param-out ?string $warnings + * Reads an image from a file and returns its type in $type. * @throws Nette\NotSupportedException if gd extension is not loaded * @throws UnknownImageFileException if file not found or file type is not known */ - public static function fromFile(string $file, ?int &$type = null, ?string &$warnings = self::Sentinel): static + public static function fromFile(string $file, ?int &$type = null): static { self::ensureExtension(); $type = self::detectTypeFromFile($file); @@ -173,18 +175,16 @@ class Image throw new UnknownImageFileException(is_file($file) ? "Unknown type of file '$file'." : "File '$file' not found."); } - return self::invokeSafe('imagecreatefrom' . self::Formats[$type], $file, "Unable to open file '$file'.", __METHOD__, $warnings); + return self::invokeSafe('imagecreatefrom' . self::Formats[$type], $file, "Unable to open file '$file'.", __METHOD__); } /** - * Reads an image from a string and returns its type in $type. If $warnings is passed, recoverable decoder - * warnings are returned in it instead of being raised as a PHP warning. - * @param-out ?string $warnings + * Reads an image from a string and returns its type in $type. * @throws Nette\NotSupportedException if gd extension is not loaded * @throws ImageException */ - public static function fromString(string $s, ?int &$type = null, ?string &$warnings = self::Sentinel): static + public static function fromString(string $s, ?int &$type = null): static { self::ensureExtension(); $type = self::detectTypeFromString($s); @@ -192,31 +192,21 @@ class Image throw new UnknownImageFileException('Unknown type of image.'); } - return self::invokeSafe('imagecreatefromstring', $s, 'Unable to open image from string.', __METHOD__, $warnings); + return self::invokeSafe('imagecreatefromstring', $s, 'Unable to open image from string.', __METHOD__); } - /** @param callable-string $func */ - private static function invokeSafe( - string $func, - string $arg, - string $message, - string $callee, - ?string &$warnings = self::Sentinel, - ): static + private static function invokeSafe(string $func, string $arg, string $message, string $callee): static { $errors = []; $res = Callback::invokeSafe($func, [$arg], function (string $message) use (&$errors): void { $errors[] = $message; }); - $raiseWarning = $warnings === self::Sentinel; - $warnings = $errors ? implode(', ', $errors) : null; - if (!$res) { - throw new ImageException($message . ' Errors: ' . $warnings); - } elseif ($errors && $raiseWarning) { - trigger_error($callee . '(): ' . $warnings, E_USER_WARNING); + throw new ImageException($message . ' Errors: ' . implode(', ', $errors)); + } elseif ($errors) { + trigger_error($callee . '(): ' . implode(', ', $errors), E_USER_WARNING); } return new static($res); @@ -227,7 +217,6 @@ class Image * Creates a new true color image of the given dimensions. The default color is black. * @param positive-int $width * @param positive-int $height - * @param ImageColor|array{red: int, green: int, blue: int, alpha?: int}|null $color * @throws Nette\NotSupportedException if gd extension is not loaded */ public static function fromBlank(int $width, int $height, ImageColor|array|null $color = null): static @@ -239,9 +228,9 @@ class Image $image = new static(imagecreatetruecolor($width, $height)); if ($color) { - $image->alphaBlending(false); - $image->filledRectangle(0, 0, $width - 1, $height - 1, self::normalizeColor($color)); - $image->alphaBlending(true); + $image->alphablending(false); + $image->filledrectangle(0, 0, $width - 1, $height - 1, $color); + $image->alphablending(true); } return $image; @@ -250,11 +239,9 @@ class Image /** * Returns the type of image from file. - * @param-out ?int $width - * @param-out ?int $height - * @return ?ImageType::* + * @return ImageType::*|null */ - public static function detectTypeFromFile(string $file, mixed &$width = null, mixed &$height = null): ?int + public static function detectTypeFromFile(string $file, &$width = null, &$height = null): ?int { [$width, $height, $type] = Helpers::falseToNull(@getimagesize($file)); // @ - files smaller than 12 bytes causes read error return $type && isset(self::Formats[$type]) ? $type : null; @@ -263,11 +250,9 @@ class Image /** * Returns the type of image from string. - * @param-out ?int $width - * @param-out ?int $height - * @return ?ImageType::* + * @return ImageType::*|null */ - public static function detectTypeFromString(string $s, mixed &$width = null, mixed &$height = null): ?int + public static function detectTypeFromString(string $s, &$width = null, &$height = null): ?int { [$width, $height, $type] = Helpers::falseToNull(@getimagesizefromstring($s)); // @ - strings smaller than 12 bytes causes read error return $type && isset(self::Formats[$type]) ? $type : null; @@ -316,7 +301,6 @@ class Image /** - * Checks whether the given image type is supported by the GD extension. * @param ImageType::* $type */ public static function isTypeSupported(int $type): bool @@ -327,17 +311,14 @@ class Image ImageType::PNG => IMG_PNG, ImageType::GIF => IMG_GIF, ImageType::WEBP => IMG_WEBP, - ImageType::AVIF => IMG_AVIF, + ImageType::AVIF => 256, // IMG_AVIF, ImageType::BMP => IMG_BMP, default => 0, }); } - /** - * Returns list of image types supported by the GD extension. - * @return ImageType::*[] - */ + /** @return ImageType[] */ public static function getSupportedTypes(): array { self::ensureExtension(); @@ -347,7 +328,7 @@ class Image $flag & IMG_JPG ? ImageType::JPEG : null, $flag & IMG_PNG ? ImageType::PNG : null, $flag & IMG_WEBP ? ImageType::WEBP : null, - $flag & IMG_AVIF ? ImageType::AVIF : null, + $flag & 256 ? ImageType::AVIF : null, // IMG_AVIF $flag & IMG_BMP ? ImageType::BMP : null, ]); } @@ -409,10 +390,6 @@ class Image public function resize(int|string|null $width, int|string|null $height, int $mode = self::OrSmaller): static { if ($mode & self::Cover) { - if ($width === null || $height === null) { - throw new Nette\InvalidArgumentException('Both width and height must be set for Cover mode.'); - } - return $this->resize($width, $height, self::OrBigger)->crop('50%', '50%', $width, $height); } @@ -446,13 +423,12 @@ class Image /** * Calculates dimensions of resized image. Width and height accept pixels or percent. * @param int-mask-of<self::OrSmaller|self::OrBigger|self::Stretch|self::Cover|self::ShrinkOnly> $mode - * @return array{int<1, max>, int<1, max>} */ public static function calculateSize( int $srcWidth, int $srcHeight, - int|string|null $newWidth, - int|string|null $newHeight, + $newWidth, + $newHeight, int $mode = self::OrSmaller, ): array { @@ -496,19 +472,19 @@ class Image } if ($mode & self::OrBigger) { - $scale = [max($scale ?: [1])]; + $scale = [max($scale)]; } if ($mode & self::ShrinkOnly) { $scale[] = 1; } - $scale = min($scale ?: [1]); + $scale = min($scale); $newWidth = (int) round($srcWidth * $scale); $newHeight = (int) round($srcHeight * $scale); } - return [max((int) $newWidth, 1), max((int) $newHeight, 1)]; + return [max($newWidth, 1), max($newHeight, 1)]; } @@ -523,7 +499,7 @@ class Image $this->image = imagecrop($this->image, $r); imagesavealpha($this->image, true); } else { - $newImage = static::fromBlank(max(1, $r['width']), max(1, $r['height']), ImageColor::rgb(0, 0, 0, 0))->getImageResource(); + $newImage = static::fromBlank($r['width'], $r['height'], ImageColor::rgb(0, 0, 0, 0))->getImageResource(); imagecopy($newImage, $this->image, 0, 0, $r['x'], $r['y'], $r['width'], $r['height']); $this->image = $newImage; } @@ -534,7 +510,6 @@ class Image /** * Calculates dimensions of cutout in image. Arguments accepts pixels or percent. - * @return array{int, int, int, int} */ public static function calculateCutout( int $srcWidth, @@ -545,10 +520,21 @@ class Image int|string $newHeight, ): array { - $newWidth = (int) (self::isPercent($newWidth) ? round($srcWidth / 100 * $newWidth) : $newWidth); - $newHeight = (int) (self::isPercent($newHeight) ? round($srcHeight / 100 * $newHeight) : $newHeight); - $left = (int) (self::isPercent($left) ? round(($srcWidth - $newWidth) / 100 * $left) : $left); - $top = (int) (self::isPercent($top) ? round(($srcHeight - $newHeight) / 100 * $top) : $top); + if (self::isPercent($newWidth)) { + $newWidth = (int) round($srcWidth / 100 * $newWidth); + } + + if (self::isPercent($newHeight)) { + $newHeight = (int) round($srcHeight / 100 * $newHeight); + } + + if (self::isPercent($left)) { + $left = (int) round(($srcWidth - $newWidth) / 100 * $left); + } + + if (self::isPercent($top)) { + $top = (int) round(($srcHeight - $newHeight) / 100 * $top); + } if ($left < 0) { $newWidth += $left; @@ -593,8 +579,14 @@ class Image $width = $image->getWidth(); $height = $image->getHeight(); - $left = (int) (self::isPercent($left) ? round(($this->getWidth() - $width) / 100 * $left) : $left); - $top = (int) (self::isPercent($top) ? round(($this->getHeight() - $height) / 100 * $top) : $top); + + if (self::isPercent($left)) { + $left = (int) round(($this->getWidth() - $width) / 100 * $left); + } + + if (self::isPercent($top)) { + $top = (int) round(($this->getHeight() - $height) / 100 * $top); + } $output = $input = $image->image; if ($opacity < 100) { @@ -607,15 +599,15 @@ class Image imagealphablending($output, false); if (!$image->isTrueColor()) { $input = $output; - imagefilledrectangle($output, 0, 0, $width, $height, (int) imagecolorallocatealpha($output, 0, 0, 0, 127)); + imagefilledrectangle($output, 0, 0, $width, $height, imagecolorallocatealpha($output, 0, 0, 0, 127)); imagecopy($output, $image->image, 0, 0, 0, 0, $width, $height); } for ($x = 0; $x < $width; $x++) { for ($y = 0; $y < $height; $y++) { - $c = \imagecolorat($input, $x, $y); + $c = imagecolorat($input, $x, $y); $c = ($c & 0xFFFFFF) + ($tbl[$c >> 24] << 24); - \imagesetpixel($output, $x, $y, $c); + imagesetpixel($output, $x, $y, $c); } } @@ -638,8 +630,6 @@ class Image /** * Calculates the bounding box for a TrueType text. Returns keys left, top, width and height. - * @param array<string, mixed> $options - * @return array{left: int, top: int, width: int, height: int} */ public static function calculateTextBox( string $text, @@ -661,7 +651,7 @@ class Image /** - * Draws a rectangle using top-left coordinates and dimensions instead of two corner coordinates. + * Draw a rectangle. */ public function rectangleWH(int $x, int $y, int $width, int $height, ImageColor $color): void { @@ -672,7 +662,7 @@ class Image /** - * Draws a filled rectangle using top-left coordinates and dimensions instead of two corner coordinates. + * Draw a filled rectangle. */ public function filledRectangleWH(int $x, int $y, int $width, int $height, ImageColor $color): void { @@ -683,8 +673,8 @@ class Image /** - * Saves image to the file. Quality is in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9). - * @param ?ImageType::* $type + * Saves image to the file. Quality is 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30), 0..9 for PNG (default 9). + * @param ImageType::*|null $type * @throws ImageException */ public function save(string $file, ?int $quality = null, ?int $type = null): void @@ -695,7 +685,7 @@ class Image /** - * Outputs image to string. Quality is in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9). + * Outputs image to string. Quality is 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30), 0..9 for PNG (default 9). * @param ImageType::* $type */ public function toString(int $type = ImageType::JPEG, ?int $quality = null): string @@ -716,7 +706,7 @@ class Image /** - * Outputs image to browser. Quality is in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9). + * Outputs image to browser. Quality is 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30), 0..9 for PNG (default 9). * @param ImageType::* $type * @throws ImageException */ @@ -751,7 +741,7 @@ class Image Callback::invokeSafe('image' . self::Formats[$type], $args, function (string $message) use ($file): void { if ($file !== null) { - @unlink($file); + @unlink($file); // @ file may not exist } throw new ImageException($message); }); @@ -760,7 +750,6 @@ class Image /** * Call to undefined method. - * @param mixed[] $args * @throws Nette\MemberAccessException */ public function __call(string $name, array $args): mixed @@ -775,7 +764,6 @@ class Image $args[$key] = $value->getImageResource(); } elseif ($value instanceof ImageColor || (is_array($value) && isset($value['red']))) { - /** @var ImageColor|array{red: int, green: int, blue: int, alpha?: int} $value */ $args[$key] = $this->resolveColor($value); } } @@ -791,11 +779,10 @@ class Image { ob_start(fn() => ''); imagepng($this->image, null, 0); - $this->setImageResource(imagecreatefromstring(ob_get_clean()) ?: throw new Nette\ShouldNotHappenException); + $this->setImageResource(imagecreatefromstring(ob_get_clean())); } - /** @param-out int|float $num */ private static function isPercent(int|string &$num): bool { if (is_string($num) && str_ends_with($num, '%')) { @@ -819,31 +806,13 @@ class Image } - /** - * Resolves a color to a GD color index for the current image. - * @param ImageColor|array{red: int, green: int, blue: int, alpha?: int} $color - */ public function resolveColor(ImageColor|array $color): int { - $color = self::normalizeColor($color)->toRGBA(); + $color = $color instanceof ImageColor ? $color->toRGBA() : array_values($color); return imagecolorallocatealpha($this->image, ...$color) ?: imagecolorresolvealpha($this->image, ...$color); } - /** @param ImageColor|array{red: int, green: int, blue: int, alpha?: int} $color */ - private static function normalizeColor(ImageColor|array $color): ImageColor - { - return $color instanceof ImageColor - ? $color - : ImageColor::rgb( - $color['red'], - $color['green'], - $color['blue'], - (127 - ($color['alpha'] ?? 0)) / 127, - ); - } - - private static function ensureExtension(): void { if (!extension_loaded('gd')) { diff --git a/vendor/nette/utils/src/Utils/ImageColor.php b/vendor/nette/utils/src/Utils/ImageColor.php index 31cf542..284ab8c 100644 --- a/vendor/nette/utils/src/Utils/ImageColor.php +++ b/vendor/nette/utils/src/Utils/ImageColor.php @@ -8,7 +8,7 @@ namespace Nette\Utils; use Nette; -use function hexdec, ltrim, max, min, round, strlen; +use function strlen; /** @@ -16,9 +16,6 @@ use function hexdec, ltrim, max, min, round, strlen; */ class ImageColor { - /** - * Creates a color from RGB components (0..255) and opacity (0..1). - */ public static function rgb(int $red, int $green, int $blue, float $opacity = 1): self { return new self($red, $green, $blue, $opacity); @@ -65,10 +62,6 @@ class ImageColor } - /** - * Returns GD-compatible color array [R, G, B, alpha]. - * @return array{int<0, 255>, int<0, 255>, int<0, 255>, int<0, 127>} - */ public function toRGBA(): array { return [ diff --git a/vendor/nette/utils/src/Utils/ImageType.php b/vendor/nette/utils/src/Utils/ImageType.php index 793f73a..89c2790 100644 --- a/vendor/nette/utils/src/Utils/ImageType.php +++ b/vendor/nette/utils/src/Utils/ImageType.php @@ -7,13 +7,11 @@ namespace Nette\Utils; -use const IMAGETYPE_BMP, IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_WEBP; - /** * Type of image file. */ -/*enum*/ final class ImageType +/* enum */ final class ImageType { public const JPEG = IMAGETYPE_JPEG, diff --git a/vendor/nette/utils/src/Utils/Iterables.php b/vendor/nette/utils/src/Utils/Iterables.php index ae414b7..f98466b 100644 --- a/vendor/nette/utils/src/Utils/Iterables.php +++ b/vendor/nette/utils/src/Utils/Iterables.php @@ -20,7 +20,6 @@ final class Iterables /** * Tests for the presence of value. - * @param iterable<mixed> $iterable */ public static function contains(iterable $iterable, mixed $value): bool { @@ -35,7 +34,6 @@ final class Iterables /** * Tests for the presence of key. - * @param iterable<mixed> $iterable */ public static function containsKey(iterable $iterable, mixed $key): bool { @@ -49,14 +47,12 @@ final class Iterables /** - * Returns the first item (matching the specified predicate if given). If there is no such item, it returns result of invoking $else or null. + * Returns the first item (matching the predicate if given). If there is no such item, returns the result of $else or null. * @template K * @template V - * @template E * @param iterable<K, V> $iterable * @param ?callable(V, K, iterable<K, V>): bool $predicate - * @param ?callable(): E $else - * @return ($else is null ? ?V : V|E) + * @return ?V */ public static function first(iterable $iterable, ?callable $predicate = null, ?callable $else = null): mixed { @@ -70,14 +66,12 @@ final class Iterables /** - * Returns the key of first item (matching the specified predicate if given). If there is no such item, it returns result of invoking $else or null. + * Returns the key of the first item (matching the predicate if given). If there is no such item, returns the result of $else or null. * @template K * @template V - * @template E * @param iterable<K, V> $iterable * @param ?callable(V, K, iterable<K, V>): bool $predicate - * @param ?callable(): E $else - * @return ($else is null ? ?K : K|E) + * @return ?K */ public static function firstKey(iterable $iterable, ?callable $predicate = null, ?callable $else = null): mixed { @@ -91,7 +85,7 @@ final class Iterables /** - * Tests whether at least one element in the iterable passes the test implemented by the provided function. + * Tests whether at least one element in the iterator passes the test implemented by the provided function. * @template K * @template V * @param iterable<K, V> $iterable @@ -109,7 +103,7 @@ final class Iterables /** - * Tests whether all elements in the iterable pass the test implemented by the provided function. + * Tests whether all elements in the iterator pass the test implemented by the provided function. * @template K * @template V * @param iterable<K, V> $iterable @@ -127,7 +121,7 @@ final class Iterables /** - * Returns a generator that yields only elements matching the given $predicate. Maintains original keys. + * Iterator that filters elements according to a given $predicate. Maintains original keys. * @template K * @template V * @param iterable<K, V> $iterable @@ -145,7 +139,7 @@ final class Iterables /** - * Returns a generator that transforms values by calling $transformer. Maintains original keys. + * Iterator that transforms values by calling $transformer. Maintains original keys. * @template K * @template V * @template R @@ -162,14 +156,14 @@ final class Iterables /** - * Returns a generator that transforms keys and values by calling $transformer. If it returns null, the element is skipped. + * Iterator that transforms keys and values by calling $transformer. If it returns null, the element is skipped. * @template K * @template V - * @template ResK * @template ResV + * @template ResK * @param iterable<K, V> $iterable - * @param callable(V, K, iterable<K, V>): ?array{ResK, ResV} $transformer - * @return \Generator<ResK, ResV> + * @param callable(V, K, iterable<K, V>): ?array{ResV, ResK} $transformer + * @return \Generator<ResV, ResK> */ public static function mapWithKeys(iterable $iterable, callable $transformer): \Generator { @@ -192,10 +186,9 @@ final class Iterables */ public static function repeatable(callable $factory): \IteratorAggregate { - return new class ($factory(...)) implements \IteratorAggregate { + return new class ($factory) implements \IteratorAggregate { public function __construct( - /** @var \Closure(): iterable<mixed, mixed> */ - private readonly \Closure $factory, + private $factory, ) { } @@ -220,8 +213,7 @@ final class Iterables { return new class (self::toIterator($iterable)) implements \IteratorAggregate { public function __construct( - private readonly \Iterator $iterator, - /** @var array<array{mixed, mixed}> */ + private \Iterator $iterator, private array $cache = [], ) { } diff --git a/vendor/nette/utils/src/Utils/Json.php b/vendor/nette/utils/src/Utils/Json.php index 4103d8b..4783d57 100644 --- a/vendor/nette/utils/src/Utils/Json.php +++ b/vendor/nette/utils/src/Utils/Json.php @@ -8,8 +8,8 @@ namespace Nette\Utils; use Nette; -use function is_int, json_decode, json_encode, json_last_error, json_last_error_msg; -use const JSON_BIGINT_AS_STRING, JSON_FORCE_OBJECT, JSON_HEX_AMP, JSON_HEX_APOS, JSON_HEX_QUOT, JSON_HEX_TAG, JSON_OBJECT_AS_ARRAY, JSON_PRESERVE_ZERO_FRACTION, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE; +use function defined, is_int; +use const JSON_HEX_AMP, JSON_HEX_APOS, JSON_HEX_QUOT, JSON_HEX_TAG; /** @@ -30,8 +30,8 @@ final class Json /** - * Converts value to JSON format. Use $pretty for formatted output, $asciiSafe for ASCII-only output, - * $htmlSafe for HTML-safe output, and $forceObjects to encode non-associative arrays as objects. + * Converts value to JSON format. Use $pretty for easier reading and clarity, $asciiSafe for ASCII output + * and $htmlSafe for HTML escaping, $forceObjects enforces the encoding of non-associateve arrays as objects. * @throws JsonException */ public static function encode( @@ -43,7 +43,7 @@ final class Json ): string { if (is_int($pretty)) { // back compatibility - $flags = ($pretty & self::ESCAPE_UNICODE ? 0 : JSON_UNESCAPED_UNICODE) | ($pretty & ~self::ESCAPE_UNICODE); + $flags = ($pretty & self::ESCAPE_UNICODE ? 0 : JSON_UNESCAPED_UNICODE) | ($pretty & ~self::ESCAPE_UNICODE); // dresscode:ignore upgrading.declarations.deprecatedMember } else { $flags = ($asciiSafe ? 0 : JSON_UNESCAPED_UNICODE) | ($pretty ? JSON_PRETTY_PRINT : 0) @@ -51,7 +51,8 @@ final class Json | ($htmlSafe ? JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_TAG : 0); } - $flags |= JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION; + $flags |= JSON_UNESCAPED_SLASHES + | (defined('JSON_PRESERVE_ZERO_FRACTION') ? JSON_PRESERVE_ZERO_FRACTION : 0); // since PHP 5.6.6 & PECL JSON-C 1.3.7 $json = json_encode($value, $flags); if ($error = json_last_error()) { @@ -63,7 +64,7 @@ final class Json /** - * Decodes a JSON string to a PHP value. Use $forceArrays to decode objects as arrays. + * Parses JSON to PHP value. The $forceArrays enforces the decoding of objects as arrays. * @throws JsonException */ public static function decode(string $json, bool|int $forceArrays = false): mixed diff --git a/vendor/nette/utils/src/Utils/ObjectHelpers.php b/vendor/nette/utils/src/Utils/ObjectHelpers.php index 03e61ce..fccec2e 100644 --- a/vendor/nette/utils/src/Utils/ObjectHelpers.php +++ b/vendor/nette/utils/src/Utils/ObjectHelpers.php @@ -9,8 +9,7 @@ namespace Nette\Utils; use Nette; use Nette\MemberAccessException; -use function array_filter, array_merge, array_pop, array_unique, get_class_methods, get_parent_class, implode, is_a, levenshtein, method_exists, preg_match_all, preg_replace, strlen, ucfirst; -use const PREG_SET_ORDER, SORT_REGULAR; +use function strlen; /** @@ -148,7 +147,11 @@ final class ObjectHelpers && ($rm = $rc->getMethod($nm))->name === $nm && !$rm->isPrivate() && !$rm->isStatic(); if ($read || $write) { - $props[$name] = $read << 0 | ($nm[0] === 'g') << 1 | $rm->returnsReference() << 2 | $write << 3 | ($type === '-deprecated') << 4; + $props[$name] = $read << 0 + | ($nm[0] === 'g') << 1 + | $rm->returnsReference() << 2 + | $write << 3 + | ($type === '-deprecated') << 4; } } @@ -179,7 +182,8 @@ final class ObjectHelpers if ($item !== $value && ( ($len = levenshtein($item, $value, 10, 11, 10)) < $min || ($len = levenshtein(preg_replace($re, '*', $item), $norm, 10, 11, 10)) < $min - )) { + ) + ) { $min = $len; $best = $item; } diff --git a/vendor/nette/utils/src/Utils/Paginator.php b/vendor/nette/utils/src/Utils/Paginator.php index e95df0d..0fff74f 100644 --- a/vendor/nette/utils/src/Utils/Paginator.php +++ b/vendor/nette/utils/src/Utils/Paginator.php @@ -15,17 +15,17 @@ use Nette; * * @property int $page * @property-read int $firstPage - * @property-read ?int $lastPage + * @property-read int|null $lastPage * @property-read int<0,max> $firstItemOnPage * @property-read int<0,max> $lastItemOnPage * @property int $base * @property-read bool $first * @property-read bool $last - * @property-read ?int<0,max> $pageCount + * @property-read int<0,max>|null $pageCount * @property positive-int $itemsPerPage - * @property ?int<0,max> $itemCount + * @property int<0,max>|null $itemCount * @property-read int<0,max> $offset - * @property-read ?int<0,max> $countdownOffset + * @property-read int<0,max>|null $countdownOffset * @property-read int<0,max> $length */ class Paginator @@ -39,10 +39,13 @@ class Paginator private int $page = 1; - /** @var ?int<0, max> */ + /** @var int<0, max>|null */ private ?int $itemCount = null; + /** + * Sets current page number. + */ public function setPage(int $page): static { $this->page = $page; @@ -50,18 +53,27 @@ class Paginator } + /** + * Returns current page number. + */ public function getPage(): int { return $this->base + $this->getPageIndex(); } + /** + * Returns first page number. + */ public function getFirstPage(): int { return $this->base; } + /** + * Returns last page number. + */ public function getLastPage(): ?int { return $this->itemCount === null @@ -71,7 +83,7 @@ class Paginator /** - * Returns the 1-based index of the first item on the current page, or 0 if the page is empty. + * Returns the sequence number of the first element on the page * @return int<0, max> */ public function getFirstItemOnPage(): int @@ -83,7 +95,7 @@ class Paginator /** - * Returns the 1-based index of the last item on the current page. + * Returns the sequence number of the last element on the page * @return int<0, max> */ public function getLastItemOnPage(): int @@ -92,6 +104,9 @@ class Paginator } + /** + * Sets first page (base) number. + */ public function setBase(int $base): static { $this->base = $base; @@ -99,6 +114,9 @@ class Paginator } + /** + * Returns first page (base) number. + */ public function getBase(): int { return $this->base; @@ -118,12 +136,18 @@ class Paginator } + /** + * Is the current page the first one? + */ public function isFirst(): bool { return $this->getPageIndex() === 0; } + /** + * Is the current page the last one? + */ public function isLast(): bool { return $this->itemCount === null @@ -133,16 +157,20 @@ class Paginator /** - * @return ?int<0, max> + * Returns the total number of pages. + * @return int<0, max>|null */ public function getPageCount(): ?int { return $this->itemCount === null ? null - : max(0, (int) ceil($this->itemCount / $this->itemsPerPage)); + : (int) ceil($this->itemCount / $this->itemsPerPage); } + /** + * Sets the number of items to display on a single page. + */ public function setItemsPerPage(int $itemsPerPage): static { $this->itemsPerPage = max(1, $itemsPerPage); @@ -151,6 +179,7 @@ class Paginator /** + * Returns the number of items to display on a single page. * @return positive-int */ public function getItemsPerPage(): int @@ -159,6 +188,9 @@ class Paginator } + /** + * Sets the total number of items. + */ public function setItemCount(?int $itemCount = null): static { $this->itemCount = $itemCount === null ? null : max(0, $itemCount); @@ -167,7 +199,8 @@ class Paginator /** - * @return ?int<0, max> + * Returns the total number of items. + * @return int<0, max>|null */ public function getItemCount(): ?int { @@ -187,7 +220,7 @@ class Paginator /** * Returns the absolute index of the first item on current page in countdown paging. - * @return ?int<0, max> + * @return int<0, max>|null */ public function getCountdownOffset(): ?int { @@ -205,6 +238,6 @@ class Paginator { return $this->itemCount === null ? $this->itemsPerPage - : max(0, min($this->itemsPerPage, $this->itemCount - $this->getPageIndex() * $this->itemsPerPage)); + : min($this->itemsPerPage, $this->itemCount - $this->getPageIndex() * $this->itemsPerPage); } } diff --git a/vendor/nette/utils/src/Utils/Process.php b/vendor/nette/utils/src/Utils/Process.php deleted file mode 100644 index c0f90bc..0000000 --- a/vendor/nette/utils/src/Utils/Process.php +++ /dev/null @@ -1,560 +0,0 @@ -<?php declare(strict_types=1); - -/** - * This file is part of the Nette Framework (https://nette.org) - * Copyright (c) 2004 David Grudl (https://davidgrudl.com) - */ - -namespace Nette\Utils; - -use Nette; -use function is_resource, is_string, strlen; -use const PHP_VERSION_ID; - - -/** - * Represents a process, which can be started and controlled (reading output, writing input, waiting for completion). - */ -final class Process -{ - private const PollInterval = 10_000; - private const DefaultTimeout = 60; - private const StdIn = 0; - private const StdOut = 1; - private const StdErr = 2; - - /** @var resource */ - private mixed $process; - - /** @var array<string, mixed> result of proc_get_status() */ - private array $status = ['running' => true]; - - /** @var resource */ - private mixed $inputPipe; - - /** @var array<int, resource|string[]> pipe resources, or ['file', path, mode] descriptors for discarded output */ - private array $outputPipes = []; - - /** @var string[] */ - private array $outputBuffers = []; - - /** @var int[] Number of bytes already read from buffers. */ - private array $outputBufferOffsets = []; - - /** @var array<int, true> Output IDs whose target resource was supplied by the caller and must not be closed here. */ - private array $callerOutputs = []; - - /** @var array<int, true> Output IDs whose pipe is backed by a temporary file (Windows < 8.5 workaround). */ - private array $fileBackedOutputs = []; - private float $startTime; - private bool $detached = false; - - - /** - * Starts an executable with given arguments. Because the arguments are passed as an array, the shell is - * never involved, so they need no escaping and there is no risk of shell injection. - * @param string $executable Path to the executable binary. - * @param list<string> $arguments Arguments passed to the executable. - * @param string[]|null $env Environment variables or null to use the same environment as the current process. - * @param array<string, mixed> $options Additional options for proc_open(). On Windows the executable is launched directly, without cmd.exe. - * @param mixed $stdin Input: string, a readable resource (its content is copied to STDIN), a Process (its STDOUT is piped in), or null (STDIN stays open for writeStdInput()). - * @param mixed $stdout Output target: string filename, a writable resource backed by a real OS file descriptor (not php://memory etc.), false to discard, or null to capture into memory. - * @param mixed $stderr Error output target (same options as $stdout). - * @param string|null $directory Working directory. - * @param float|null $timeout Time limit in seconds, checked while waiting for or reading the process; null disables it. - */ - public static function runExecutable( - string $executable, - array $arguments = [], - ?array $env = null, - array $options = [], - mixed $stdin = '', - mixed $stdout = null, - mixed $stderr = null, - ?string $directory = null, - ?float $timeout = self::DefaultTimeout, - ): self - { - return new self([$executable, ...$arguments], $env, $options, $directory, $stdin, $stdout, $stderr, $timeout); - } - - - /** - * Starts a process from a command string interpreted by the shell (/bin/sh on POSIX, cmd.exe on Windows). - * Because the shell parses the string, NEVER pass unescaped user input here - use runExecutable() for that. - * @param string $command Shell command to run. - * @param string[]|null $env Environment variables or null to use the same environment as the current process. - * @param array<string, mixed> $options Options for proc_open(), e.g. ['bypass_shell' => true] on Windows to skip cmd.exe. - * @param mixed $stdin Input: string, a readable resource (its content is copied to STDIN), a Process (its STDOUT is piped in), or null (STDIN stays open for writeStdInput()). - * @param mixed $stdout Output target: string filename, a writable resource backed by a real OS file descriptor (not php://memory etc.), false to discard, or null to capture into memory. - * @param mixed $stderr Error output target (same options as $stdout). - * @param string|null $directory Working directory. - * @param float|null $timeout Time limit in seconds, checked while waiting for or reading the process; null disables it. - */ - public static function runCommand( - string $command, - ?array $env = null, - array $options = [], - mixed $stdin = '', - mixed $stdout = null, - mixed $stderr = null, - ?string $directory = null, - ?float $timeout = self::DefaultTimeout, - ): self - { - return new self($command, $env, $options, $directory, $stdin, $stdout, $stderr, $timeout); - } - - - /** - * @param list<string>|string $command - * @param array<string, string>|null $env - * @param array<string, mixed> $options - */ - private function __construct( - string|array $command, - ?array $env, - array $options, - ?string $directory, - mixed $stdin, - mixed $stdout, - mixed $stderr, - private readonly ?float $timeout, - ) { - $descriptors = [ - self::StdIn => $this->createInputDescriptor($stdin), - self::StdOut => $this->createOutputDescriptor(self::StdOut, $stdout), - self::StdErr => $this->createOutputDescriptor(self::StdErr, $stderr), - ]; - - $process = @proc_open($command, $descriptors, $pipes, $directory, $env, $options); - if (!is_resource($process)) { - throw new ProcessFailedException('Failed to start process: ' . Helpers::getLastError()); - } - - $this->process = $process; - [$this->inputPipe, $this->outputPipes[self::StdOut], $this->outputPipes[self::StdErr]] = $pipes + $descriptors; - - if ($stdin instanceof self) { - // the source process hands over its STDOUT pipe; from now on this process owns it - unset( - $stdin->outputBuffers[self::StdOut], - $stdin->outputBufferOffsets[self::StdOut], - $stdin->outputPipes[self::StdOut], - ); - } - - $this->writeInitialInput($stdin); - $this->startTime = microtime(true); - } - - - public function __destruct() - { - if ($this->detached) { - return; - } - $this->outputBuffers = []; - $this->terminate(); - } - - - /** - * Detaches the process: it keeps running in the background and is not terminated when the object - * is destroyed. STDIN and output pipes are closed, so the output must not be captured in memory - * (pass a file name, a resource or false as $stdout/$stderr). Only the destructor behavior changes: - * wait() and getExitCode() still block ($timeout still applies) and terminate() still kills it. - * On POSIX, a detached child that exits early stays a zombie until the script ends. - */ - public function detach(): void - { - if ($this->outputBuffers !== []) { - throw new Nette\InvalidStateException('Cannot detach process: its output is captured in memory, pass a file name, a resource or false as $stdout/$stderr.'); - } - $this->detached = true; - $this->closeStdInput(); - $this->closeOutputPipes(); - } - - - /** - * Checks if the process is currently running. - */ - public function isRunning(): bool - { - if (!$this->status['running']) { - return false; - } - - $this->status = proc_get_status($this->process); - if (!$this->status['running']) { - $this->close(); - } - - return $this->status['running']; - } - - - /** - * Finishes the process by waiting for its completion. While waiting, the captured output is read - * continuously and kept in memory; an optional callback is invoked with each new output/error chunk. - * - * @param (\Closure(string, string): void)|null $callback - */ - public function wait(?\Closure $callback = null): void - { - while ($this->isRunning()) { - $this->enforceTimeout(); - $this->drainPipes(); - $this->dispatchCallback($callback); - usleep(self::PollInterval); - } - - $this->dispatchCallback($callback); - } - - - /** - * Reads any new data from the captured pipes into the buffers, so a process producing more output - * than the OS pipe buffer holds does not block. With $final (process already finished) reads to EOF. - */ - private function drainPipes(bool $final = false): void - { - foreach ([self::StdOut, self::StdErr] as $id) { - $this->readFromPipe($id, $final); - } - } - - - /** - * Terminates the running process if it is still running. - */ - public function terminate(): void - { - if (!$this->isRunning()) { - return; - } elseif (Helpers::IsWindows) { - exec("taskkill /F /T /PID {$this->getPid()} 2>&1"); - } else { - proc_terminate($this->process, 9); // 9 = SIGKILL: cannot be trapped, so the following proc_close() won't hang - } - $this->status['running'] = false; - $this->close(); - } - - - /** - * Returns the process exit code. If the process is still running, waits until it finishes. - */ - public function getExitCode(): int - { - $this->wait(); - return $this->status['exitcode'] ?? -1; - } - - - /** - * Returns true if the process terminated with exit code 0. - */ - public function isSuccess(): bool - { - return $this->getExitCode() === 0; - } - - - /** - * Waits for the process to finish and throws ProcessFailedException if exit code is not zero. - */ - public function ensureSuccess(): void - { - $code = $this->getExitCode(); - if ($code !== 0) { - throw new ProcessFailedException("Process failed with non-zero exit code: $code"); - } - } - - - /** - * Returns the PID of the running process, or null if it is not running. - */ - public function getPid(): ?int - { - return $this->isRunning() ? $this->status['pid'] : null; - } - - - /** - * Waits for the process to finish and returns everything it wrote to STDOUT. - */ - public function getStdOutput(): string - { - $this->wait(); - return $this->outputBuffers[self::StdOut] ?? throw new Nette\InvalidStateException('Cannot read output: it is not captured (it was redirected, discarded or piped).'); - } - - - /** - * Waits for the process to finish and returns everything it wrote to STDERR. - */ - public function getStdError(): string - { - $this->wait(); - return $this->outputBuffers[self::StdErr] ?? throw new Nette\InvalidStateException('Cannot read output: it is not captured (it was redirected, discarded or piped).'); - } - - - /** - * Returns the STDOUT data produced since the previous consumeStdOutput() call. - * To read everything incrementally, poll `while ($p->isRunning())` calling this, then call it once more - * after the loop; that last call returns whatever the process wrote just before the loop noticed it had exited. - */ - public function consumeStdOutput(): string - { - return $this->consumeBuffer(self::StdOut); - } - - - /** - * Returns the STDERR data produced since the previous consumeStdError() call. See consumeStdOutput(). - */ - public function consumeStdError(): string - { - return $this->consumeBuffer(self::StdErr); - } - - - /** - * Returns newly available data from the specified buffer and advances the read pointer. - */ - private function consumeBuffer(int $id): string - { - if (!isset($this->outputBuffers[$id])) { - throw new Nette\InvalidStateException('Cannot read output: it is not captured (it was redirected, discarded or piped).'); - } elseif ($this->isRunning()) { - $this->enforceTimeout(); - $this->readFromPipe($id); - } - return $this->extractNewData($id); - } - - - /** - * Returns the buffered data not returned yet and advances the read pointer. - */ - private function extractNewData(int $id): string - { - if (!isset($this->outputBuffers[$id])) { - return ''; - } - $res = substr($this->outputBuffers[$id], $this->outputBufferOffsets[$id]); - $this->outputBufferOffsets[$id] = strlen($this->outputBuffers[$id]); - return $res; - } - - - /** - * Writes data into the process' STDIN. If STDIN is closed, throws exception. - */ - public function writeStdInput(string $string): void - { - if (!is_resource($this->inputPipe)) { - throw new Nette\InvalidStateException('Cannot write to process: STDIN pipe is closed'); - } - $this->writeToPipe($string); - } - - - /** - * Writes the whole string to STDIN, handling partial writes. Stops (and lets fwrite() warn) on a broken pipe, - * i.e. when the process stopped reading its STDIN. - */ - private function writeToPipe(string $string): void - { - $length = strlen($string); - for ($written = 0; $written < $length; $written += $bytes) { - $bytes = fwrite($this->inputPipe, substr($string, $written)); - if (!$bytes) { - break; - } - } - } - - - /** - * Closes the STDIN pipe, indicating no more data will be sent. - */ - public function closeStdInput(): void - { - if (is_resource($this->inputPipe)) { - fclose($this->inputPipe); - } - } - - - /** - * If a callback is given, invokes it with the output/error produced since the previous call. - * @param (\Closure(string, string): void)|null $callback - */ - private function dispatchCallback(?\Closure $callback): void - { - if (!$callback) { - return; - } - $output = $this->extractNewData(self::StdOut); - $error = $this->extractNewData(self::StdErr); - if ($output !== '' || $error !== '') { - $callback($output, $error); - } - } - - - /** - * Checks if the timeout has expired. If yes, terminates the process. - */ - private function enforceTimeout(): void - { - if ($this->timeout !== null && (microtime(true) - $this->startTime) >= $this->timeout) { - $this->terminate(); - throw new ProcessTimeoutException('Process exceeded the time limit of ' . $this->timeout . ' seconds'); - } - } - - - /** - * Reads any new data from the specified pipe and appends it to the buffer. Does nothing if the output - * is not captured or the pipe is already closed (or handed over to another process). - */ - private function readFromPipe(int $id, bool $final = false): void - { - $pipe = $this->outputPipes[$id] ?? null; - if (!isset($this->outputBuffers[$id]) || !is_resource($pipe)) { - return; - - } elseif (isset($this->fileBackedOutputs[$id])) { - // Windows < 8.5: captured output is a temporary file; read whatever was appended since last time - fseek($pipe, strlen($this->outputBuffers[$id])); - $this->outputBuffers[$id] .= stream_get_contents($pipe); - - } elseif ($final) { - // the process has finished, everything is buffered in the pipe; non-blocking read on POSIX - // (cannot hang on a leaked descendant still holding the write end), blocking read to EOF on - // Windows, where non-blocking mode does not work and stream_select() may miss buffered data - stream_set_blocking($pipe, Helpers::IsWindows); - $this->outputBuffers[$id] .= stream_get_contents($pipe); - - } else { - // non-blocking drain: stream_set_blocking(false) works on POSIX only, so reads are also - // guarded by stream_select(), which works on Windows pipes since PHP 8.5 (PeekNamedPipe fix) - stream_set_blocking($pipe, false); - $read = [$pipe]; - $write = $except = []; - while (@stream_select($read, $write, $except, 0, 0) > 0) { - $chunk = fread($pipe, 8192); - if ($chunk === false || $chunk === '') { - break; - } - $this->outputBuffers[$id] .= $chunk; - $read = [$pipe]; - } - } - } - - - /** - * Sends the initial input to the process: writes and closes a string or stream input, - * or leaves STDIN open when input is null (until closeStdInput()) or another Process (fed by that process). - * The input type was already validated by createInputDescriptor(). - * - * Note: a string or stream input is written upfront, so if it is large and the process does not read it - * while filling its own output, this can block; in that case pass null and feed STDIN via writeStdInput(). - */ - private function writeInitialInput(mixed $input): void - { - if ($input === null || $input instanceof self) { - // STDIN stays open - - } elseif (is_string($input)) { - $this->writeToPipe($input); - $this->closeStdInput(); - - } elseif (is_resource($input)) { - stream_copy_to_stream($input, $this->inputPipe); - $this->closeStdInput(); - } - } - - - /** - * Validates the input and determines the STDIN descriptor based on its type. - */ - private function createInputDescriptor(mixed $input): mixed - { - if ($input === null || is_string($input) || is_resource($input)) { - return ['pipe', 'r']; - } elseif (!$input instanceof self) { - throw new Nette\InvalidArgumentException('Input must be string, resource, Process or null, ' . get_debug_type($input) . ' given.'); - } elseif (Helpers::IsWindows) { - throw new Nette\NotSupportedException('Process piping is not supported on Windows.'); - } elseif (!isset($input->outputBuffers[self::StdOut]) || !is_resource($input->outputPipes[self::StdOut] ?? null)) { - throw new Nette\InvalidStateException('Cannot pipe from the given process: its STDOUT must be captured (it must not be redirected elsewhere).'); - } - return $input->outputPipes[self::StdOut]; - } - - - /** - * Determines the descriptor for STDOUT or STDERR based on the specified output target. - */ - private function createOutputDescriptor(int $id, mixed $output): mixed - { - if (is_resource($output)) { - $this->callerOutputs[$id] = true; - return $output; - - } elseif (is_string($output)) { - return FileSystem::open($output, 'w'); - - } elseif ($output === false) { - return ['file', Helpers::IsWindows ? 'NUL' : '/dev/null', 'w']; - - } elseif ($output === null) { - $this->outputBuffers[$id] = ''; - $this->outputBufferOffsets[$id] = 0; - if (Helpers::IsWindows && PHP_VERSION_ID < 80500) { - // Windows < 8.5: stream_select() doesn't work on pipes, capture into a temp file that reads non-blockingly - $this->fileBackedOutputs[$id] = true; - return tmpfile(); - } - return ['pipe', 'w']; - - } else { - throw new Nette\InvalidArgumentException('Output must be string, resource, bool or null, ' . get_debug_type($output) . ' given.'); - } - } - - - /** - * Closes all pipes and the process resource. - */ - private function close(): void - { - $this->drainPipes(final: true); - $this->closeStdInput(); - $this->closeOutputPipes(); - proc_close($this->process); - } - - - /** - * Closes the output pipes that this class opened; resources supplied by the caller are left untouched. - * (The temporary file backing captured output on Windows < 8.5 is removed by fclose() itself.) - */ - private function closeOutputPipes(): void - { - foreach ($this->outputPipes as $id => $pipe) { - if (is_resource($pipe) && !isset($this->callerOutputs[$id])) { - fclose($pipe); - } - } - } -} diff --git a/vendor/nette/utils/src/Utils/Reflection.php b/vendor/nette/utils/src/Utils/Reflection.php index d6a7b3b..cb9b1a7 100644 --- a/vendor/nette/utils/src/Utils/Reflection.php +++ b/vendor/nette/utils/src/Utils/Reflection.php @@ -8,8 +8,8 @@ namespace Nette\Utils; use Nette; -use function constant, current, defined, end, explode, file_get_contents, implode, ltrim, next, ord, strrchr, strtolower, substr; -use const T_AS, T_CLASS, T_COMMENT, T_CURLY_OPEN, T_DOC_COMMENT, T_DOLLAR_OPEN_CURLY_BRACES, T_ENUM, T_INTERFACE, T_NAME_FULLY_QUALIFIED, T_NAME_QUALIFIED, T_NAMESPACE, T_NS_SEPARATOR, T_STRING, T_TRAIT, T_USE, T_WHITESPACE, TOKEN_PARSE; +use function ord; +use const PHP_VERSION_ID; /** @@ -26,21 +26,17 @@ final class Reflection } - #[\Deprecated('use Nette\Utils\Validators::isClassKeyword()')] + /** @deprecated use Nette\Utils\Validators::isClassKeyword() */ public static function isClassKeyword(string $name): bool { return Validators::isClassKeyword($name); } - /** - * Returns the default value of a parameter. Resolves constants and class constants used as default values. - * @throws \ReflectionException if the constant cannot be resolved - */ public static function getParameterDefaultValue(\ReflectionParameter $param): mixed { if ($param->isDefaultValueConstant()) { - $const = $orig = $param->getDefaultValueConstantName() ?? throw new Nette\ShouldNotHappenException; + $const = $orig = $param->getDefaultValueConstantName(); $pair = explode('::', $const); if (isset($pair[1])) { $pair[0] = Type::resolve($pair[0], $param); @@ -70,7 +66,6 @@ final class Reflection /** * Returns a reflection of a class or trait that contains a declaration of given property. Property can also be declared in the trait. - * @return \ReflectionClass<object> */ public static function getPropertyDeclaringClass(\ReflectionProperty $prop): \ReflectionClass { @@ -133,9 +128,6 @@ final class Reflection } - /** - * Returns a human-readable string representation of a reflection object. - */ public static function toString(\Reflector $ref): string { if ($ref instanceof \ReflectionClass) { @@ -143,7 +135,9 @@ final class Reflection } elseif ($ref instanceof \ReflectionMethod) { return $ref->getDeclaringClass()->name . '::' . $ref->name . '()'; } elseif ($ref instanceof \ReflectionFunction) { - return $ref->isAnonymous() ? '{closure}()' : $ref->name . '()'; + return PHP_VERSION_ID >= 80200 && $ref->isAnonymous() + ? '{closure}()' + : $ref->name . '()'; } elseif ($ref instanceof \ReflectionProperty) { return self::getPropertyDeclaringClass($ref)->name . '::$' . $ref->name; } elseif ($ref instanceof \ReflectionParameter) { @@ -157,7 +151,6 @@ final class Reflection /** * Expands the name of the class to full name in the given context of given class. * Thus, it returns how the PHP parser would understand $name if it were written in the body of the class $context. - * @param \ReflectionClass<object> $context * @throws Nette\InvalidArgumentException */ public static function expandClassName(string $name, \ReflectionClass $context): string @@ -196,11 +189,7 @@ final class Reflection } - /** - * Returns the use statements from the file where the class is defined. - * @param \ReflectionClass<object> $class - * @return array<string, class-string> Map of alias to fully qualified class name - */ + /** @return array<string, class-string> of [alias => class] */ public static function getUseStatements(\ReflectionClass $class): array { if ($class->isAnonymous()) { @@ -212,7 +201,7 @@ final class Reflection if ($class->isInternal()) { $cache[$name] = []; } else { - $code = (string) file_get_contents((string) $class->getFileName()); + $code = file_get_contents($class->getFileName()); $cache = self::parseUseStatements($code, $name) + $cache; } } @@ -223,14 +212,13 @@ final class Reflection /** * Parses PHP code to [class => [alias => class, ...]] - * @return array<string, array<string, string>> */ private static function parseUseStatements(string $code, ?string $forClass = null): array { try { $tokens = \PhpToken::tokenize($code, TOKEN_PARSE); } catch (\ParseError $e) { - trigger_error($e->getMessage()); + trigger_error($e->getMessage(), E_USER_NOTICE); $tokens = []; } @@ -251,7 +239,7 @@ final class Reflection case T_CLASS: case T_INTERFACE: case T_TRAIT: - case T_ENUM: + case PHP_VERSION_ID < 80100 ? T_CLASS : T_ENUM: if ($name = self::fetch($tokens, T_STRING)) { $class = $namespace . $name; $classLevel = $level + 1; @@ -268,8 +256,8 @@ final class Reflection $name = ltrim($name, '\\'); if (self::fetch($tokens, '{')) { while ($suffix = self::fetch($tokens, $nameTokens)) { - if (self::fetch($tokens, T_AS) && ($alias = self::fetch($tokens, T_STRING))) { - $uses[$alias] = $name . $suffix; + if (self::fetch($tokens, T_AS)) { + $uses[self::fetch($tokens, T_STRING)] = $name . $suffix; } else { $tmp = explode('\\', $suffix); $uses[end($tmp)] = $name . $suffix; @@ -279,8 +267,8 @@ final class Reflection break; } } - } elseif (self::fetch($tokens, T_AS) && ($alias = self::fetch($tokens, T_STRING))) { - $uses[$alias] = $name; + } elseif (self::fetch($tokens, T_AS)) { + $uses[self::fetch($tokens, T_STRING)] = $name; } else { $tmp = explode('\\', $name); @@ -313,10 +301,6 @@ final class Reflection } - /** - * @param \PhpToken[] $tokens - * @param string|int|int[] $take - */ private static function fetch(array &$tokens, string|int|array $take): ?string { $res = null; diff --git a/vendor/nette/utils/src/Utils/ReflectionMethod.php b/vendor/nette/utils/src/Utils/ReflectionMethod.php index fe2159c..dc1f9a1 100644 --- a/vendor/nette/utils/src/Utils/ReflectionMethod.php +++ b/vendor/nette/utils/src/Utils/ReflectionMethod.php @@ -7,7 +7,7 @@ namespace Nette\Utils; -use function explode, is_string, str_contains; +use function is_string; /** @@ -16,11 +16,9 @@ use function explode, is_string, str_contains; */ final class ReflectionMethod extends \ReflectionMethod { - /** @var \ReflectionClass<object> */ - private readonly \ReflectionClass $originalClass; + private \ReflectionClass $originalClass; - /** @param class-string|object $objectOrMethod */ public function __construct(object|string $objectOrMethod, ?string $method = null) { if (is_string($objectOrMethod) && str_contains($objectOrMethod, '::')) { @@ -31,7 +29,6 @@ final class ReflectionMethod extends \ReflectionMethod } - /** @return \ReflectionClass<object> */ public function getOriginalClass(): \ReflectionClass { return $this->originalClass; diff --git a/vendor/nette/utils/src/Utils/Strings.php b/vendor/nette/utils/src/Utils/Strings.php index 27bd39c..0872c92 100644 --- a/vendor/nette/utils/src/Utils/Strings.php +++ b/vendor/nette/utils/src/Utils/Strings.php @@ -9,8 +9,8 @@ namespace Nette\Utils; use JetBrains\PhpStorm\Language; use Nette; -use function array_keys, array_map, array_shift, array_values, bin2hex, class_exists, defined, extension_loaded, function_exists, htmlspecialchars, htmlspecialchars_decode, iconv, iconv_strlen, iconv_substr, implode, in_array, is_array, is_callable, is_int, is_object, is_string, key, max, mb_convert_case, mb_strlen, mb_strtolower, mb_strtoupper, mb_substr, pack, preg_last_error, preg_last_error_msg, preg_quote, preg_replace, str_contains, str_ends_with, str_repeat, str_replace, str_starts_with, strlen, strpos, strrev, strrpos, strtolower, strtoupper, strtr, substr, trim, unpack; -use const ENT_IGNORE, ENT_NOQUOTES, ICONV_IMPL, MB_CASE_TITLE, PHP_EOL, PREG_OFFSET_CAPTURE, PREG_PATTERN_ORDER, PREG_SET_ORDER, PREG_SPLIT_DELIM_CAPTURE, PREG_SPLIT_NO_EMPTY, PREG_SPLIT_OFFSET_CAPTURE, PREG_UNMATCHED_AS_NULL; +use function defined, extension_loaded, function_exists, in_array, is_array, is_int, is_object, is_string, strlen; +use const ENT_IGNORE, ENT_NOQUOTES; /** @@ -22,7 +22,7 @@ class Strings public const TrimCharacters = " \t\n\r\0\x0B\u{A0}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{200B}\u{2028}\u{3000}"; - #[\Deprecated('use Strings::TrimCharacters')] + /** @deprecated use Strings::TrimCharacters */ public const TRIM_CHARACTERS = self::TrimCharacters; @@ -57,8 +57,7 @@ class Strings throw new Nette\NotSupportedException(__METHOD__ . '() requires ICONV extension that is not loaded.'); } - $res = iconv('UTF-32BE', 'UTF-8//IGNORE', pack('N', $code)); - return $res === false ? throw new Nette\ShouldNotHappenException : $res; + return iconv('UTF-32BE', 'UTF-8//IGNORE', pack('N', $code)); } @@ -72,11 +71,11 @@ class Strings } $tmp = iconv('UTF-8', 'UTF-32BE//IGNORE', $c); - if ($tmp === false || $tmp === '') { + if (!$tmp) { throw new Nette\InvalidArgumentException('Invalid UTF-8 character "' . ($c === '' ? '' : '\x' . strtoupper(bin2hex($c))) . '".'); } - return unpack('N', $tmp)[1] ?? throw new Nette\ShouldNotHappenException; + return unpack('N', $tmp)[1]; } @@ -123,8 +122,7 @@ class Strings $start += self::length($s); // unifies iconv_substr behavior with mb_substr } - $res = iconv_substr($s, $start, $length, 'UTF-8'); - return $res === false ? throw new Nette\InvalidStateException('iconv_substr() failed.') : $res; + return iconv_substr($s, $start, $length, 'UTF-8'); } @@ -135,7 +133,7 @@ class Strings public static function normalize(string $s): string { // convert to compressed normal form (NFC) - if (class_exists('Normalizer', autoload: false) && ($n = \Normalizer::normalize($s, \Normalizer::FORM_C)) !== false) { + if (class_exists('Normalizer', false) && ($n = \Normalizer::normalize($s, \Normalizer::FORM_C)) !== false) { $s = $n; } @@ -186,39 +184,106 @@ class Strings */ public static function toAscii(string $s): string { - if (!extension_loaded('intl')) { - throw new Nette\NotSupportedException(__METHOD__ . '() requires INTL extension that is not loaded.'); - } - $iconv = defined('ICONV_IMPL') ? trim(ICONV_IMPL, '"\'') : null; + static $transliterator = null; + if ($transliterator === null) { + if (class_exists('Transliterator', false)) { + $transliterator = \Transliterator::create('Any-Latin; Latin-ASCII'); + } else { + trigger_error(__METHOD__ . "(): it is recommended to enable PHP extensions 'intl'.", E_USER_NOTICE); + $transliterator = false; + } + } // remove control characters and check UTF-8 validity $s = self::pcre('preg_replace', ['#[^\x09\x0A\x0D\x20-\x7E\xA0-\x{2FF}\x{370}-\x{10FFFF}]#u', '', $s]); // transliteration (by Transliterator and iconv) is not optimal, replace some characters directly - $s = strtr($s, ["\u{201E}" => '"', "\u{201C}" => '"', "\u{201D}" => '"', "\u{201A}" => "'", "\u{2018}" => "'", "\u{2019}" => "'", "\u{B0}" => '^', "\u{42F}" => 'Ya', "\u{44F}" => 'ya', "\u{42E}" => 'Yu', "\u{44E}" => 'yu', "\u{c4}" => 'Ae', "\u{d6}" => 'Oe', "\u{dc}" => 'Ue', "\u{1e9e}" => 'Ss', "\u{e4}" => 'ae', "\u{f6}" => 'oe', "\u{fc}" => 'ue', "\u{df}" => 'ss']); // „ “ ” ‚ ‘ ’ ° Я я Ю ю Ä Ö Ü ẞ ä ö ü ß + $s = strtr($s, [ + "\u{201E}" => '"', + "\u{201C}" => '"', + "\u{201D}" => '"', + "\u{201A}" => "'", + "\u{2018}" => "'", + "\u{2019}" => "'", + "\u{B0}" => '^', + "\u{42F}" => 'Ya', + "\u{44F}" => 'ya', + "\u{42E}" => 'Yu', + "\u{44E}" => 'yu', + "\u{c4}" => 'Ae', + "\u{d6}" => 'Oe', + "\u{dc}" => 'Ue', + "\u{1e9e}" => 'Ss', + "\u{e4}" => 'ae', + "\u{f6}" => 'oe', + "\u{fc}" => 'ue', + "\u{df}" => 'ss', + ]); // „ “ ” ‚ ‘ ’ ° Я я Ю ю Ä Ö Ü ẞ ä ö ü ß if ($iconv !== 'libiconv') { - $s = strtr($s, ["\u{AE}" => '(R)', "\u{A9}" => '(c)', "\u{2026}" => '...', "\u{AB}" => '<<', "\u{BB}" => '>>', "\u{A3}" => 'lb', "\u{A5}" => 'yen', "\u{B2}" => '^2', "\u{B3}" => '^3', "\u{B5}" => 'u', "\u{B9}" => '^1', "\u{BA}" => 'o', "\u{BF}" => '?', "\u{2CA}" => "'", "\u{2CD}" => '_', "\u{2DD}" => '"', "\u{1FEF}" => '', "\u{20AC}" => 'EUR', "\u{2122}" => 'TM', "\u{212E}" => 'e', "\u{2190}" => '<-', "\u{2191}" => '^', "\u{2192}" => '->', "\u{2193}" => 'V', "\u{2194}" => '<->']); // ® © … « » £ ¥ ² ³ µ ¹ º ¿ ˊ ˍ ˝ ` € ™ ℮ ← ↑ → ↓ ↔ + $s = strtr($s, [ + "\u{AE}" => '(R)', + "\u{A9}" => '(c)', + "\u{2026}" => '...', + "\u{AB}" => '<<', + "\u{BB}" => '>>', + "\u{A3}" => 'lb', + "\u{A5}" => 'yen', + "\u{B2}" => '^2', + "\u{B3}" => '^3', + "\u{B5}" => 'u', + "\u{B9}" => '^1', + "\u{BA}" => 'o', + "\u{BF}" => '?', + "\u{2CA}" => "'", + "\u{2CD}" => '_', + "\u{2DD}" => '"', + "\u{1FEF}" => '', + "\u{20AC}" => 'EUR', + "\u{2122}" => 'TM', + "\u{212E}" => 'e', + "\u{2190}" => '<-', + "\u{2191}" => '^', + "\u{2192}" => '->', + "\u{2193}" => 'V', + "\u{2194}" => '<->', + ]); // ® © … « » £ ¥ ² ³ µ ¹ º ¿ ˊ ˍ ˝ ` € ™ ℮ ← ↑ → ↓ ↔ } - $s = \Transliterator::create('Any-Latin; Latin-ASCII')?->transliterate($s) - ?? throw new Nette\InvalidStateException('Transliterator::transliterate() failed.'); - - // use iconv because The transliterator leaves some characters out of ASCII, eg → ʾ - if ($iconv === 'glibc') { - $s = strtr($s, '?', "\x01"); // temporarily hide ? to distinguish them from the garbage that iconv creates - $s = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s); - if ($s === false) { - throw new Nette\InvalidStateException('iconv() failed.'); + if ($transliterator) { + $s = $transliterator->transliterate($s); + // use iconv because The transliterator leaves some characters out of ASCII, eg → ʾ + if ($iconv === 'glibc') { + $s = strtr($s, '?', "\x01"); // temporarily hide ? to distinguish them from the garbage that iconv creates + $s = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s); + $s = str_replace(['?', "\x01"], ['', '?'], $s); // remove garbage and restore ? characters + } elseif ($iconv === 'libiconv') { + $s = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s); + } else { // null or 'unknown' (#216) + $s = self::pcre('preg_replace', ['#[^\x00-\x7F]++#', '', $s]); // remove non-ascii chars + } + } elseif ($iconv === 'glibc' || $iconv === 'libiconv') { + // temporarily hide these characters to distinguish them from the garbage that iconv creates + $s = strtr($s, '`\'"^~?', "\x01\x02\x03\x04\x05\x06"); + if ($iconv === 'glibc') { + // glibc implementation is very limited. transliterate into Windows-1250 and then into ASCII, + // so most Eastern European characters are preserved + $s = iconv('UTF-8', 'WINDOWS-1250//TRANSLIT//IGNORE', $s); + $s = strtr( + $s, + "\xa5\xa3\xbc\x8c\xa7\x8a\xaa\x8d\x8f\x8e\xaf\xb9\xb3\xbe\x9c\x9a\xba\x9d\x9f\x9e\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xfe\x96\xa0\x8b\x97\x9b\xa6\xad\xb7", + 'ALLSSSSTZZZallssstzzzRAAAALCCCEEEEIIDDNNOOOOxRUUUUYTsraaaalccceeeeiiddnnooooruuuuyt- <->|-.', + ); + $s = self::pcre('preg_replace', ['#[^\x00-\x7F]++#', '', $s]); + } else { + $s = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s); } - $s = str_replace(['?', "\x01"], ['', '?'], $s); // remove garbage and restore ? characters - } elseif ($iconv === 'libiconv') { - $s = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s); - if ($s === false) { - throw new Nette\InvalidStateException('iconv() failed.'); - } - } else { // null or 'unknown' (#216) + // remove garbage that iconv creates during transliteration (eg Ý -> Y') + $s = str_replace(['`', "'", '"', '^', '~', '?'], '', $s); + // restore temporarily hidden characters + $s = strtr($s, "\x01\x02\x03\x04\x05\x06", '`\'"^~?'); + } else { $s = self::pcre('preg_replace', ['#[^\x00-\x7F]++#', '', $s]); // remove non-ascii chars } @@ -332,9 +397,9 @@ class Strings */ public static function compare(string $left, string $right, ?int $length = null): bool { - if (class_exists('Normalizer', autoload: false)) { - $left = \Normalizer::normalize($left, \Normalizer::FORM_D) ?: $left; // form NFD is faster, false on invalid UTF-8 - $right = \Normalizer::normalize($right, \Normalizer::FORM_D) ?: $right; // form NFD is faster, false on invalid UTF-8 + if (class_exists('Normalizer', false)) { + $left = \Normalizer::normalize($left, \Normalizer::FORM_D); // form NFD is faster + $right = \Normalizer::normalize($right, \Normalizer::FORM_D); // form NFD is faster } if ($length < 0) { @@ -356,10 +421,6 @@ class Strings public static function findPrefix(array $strings): string { $first = array_shift($strings); - if ($first === null) { - return ''; - } - for ($i = 0; $i < strlen($first); $i++) { foreach ($strings as $s) { if (!isset($s[$i]) || $first[$i] !== $s[$i]) { @@ -383,9 +444,9 @@ class Strings public static function length(string $s): int { return match (true) { - extension_loaded('mbstring') => (int) mb_strlen($s, 'UTF-8'), - extension_loaded('iconv') => (int) iconv_strlen($s, 'UTF-8'), - default => strlen((string) preg_replace('#[\x80-\xBF]#', '', $s)), // strips UTF-8 continuation bytes + extension_loaded('mbstring') => mb_strlen($s, 'UTF-8'), + extension_loaded('iconv') => iconv_strlen($s, 'UTF-8'), + default => strlen(@utf8_decode($s)), // dresscode:ignore mistakes.errorSuppression, upgrading.php.deprecatedApi }; } @@ -433,10 +494,7 @@ class Strings throw new Nette\NotSupportedException(__METHOD__ . '() requires ICONV extension that is not loaded.'); } - $tmp = iconv('UTF-8', 'UTF-32BE', $s); - return $tmp === false - ? throw new Nette\InvalidStateException('iconv() failed.') - : (string) iconv('UTF-32LE', 'UTF-8', strrev($tmp)); + return iconv('UTF-32LE', 'UTF-8', strrev(iconv('UTF-8', 'UTF-32BE', $s))); } @@ -514,8 +572,7 @@ class Strings /** - * Splits the string by a regular expression. Expressions in parentheses will be captured and returned as well. - * @return list<string> + * Divides the string into arrays according to the regular expression. Expressions in parentheses will be captured and returned as well. */ public static function split( string $subject, @@ -540,9 +597,8 @@ class Strings /** - * Searches the string for the first match of the regular expression and returns - * an array with the found expression and individual subexpressions, or null. - * @return ?array<string> + * Searches the string for the part matching the regular expression and returns + * an array with the found expression and individual subexpressions, or `null`. */ public static function match( string $subject, @@ -563,7 +619,6 @@ class Strings $pattern .= 'u'; } - $m = []; if ($offset > strlen($subject)) { return null; } elseif (!self::pcre('preg_match', [$pattern, $subject, &$m, $flags, $offset])) { @@ -577,9 +632,9 @@ class Strings /** - * Searches the string for all occurrences matching the regular expression and returns - * an array of arrays containing the found expression and each subexpression. - * @return ($lazy is true ? \Generator<int, array<string>> : list<array<string>>) + * Searches the string for all occurrences matching the regular expression and + * returns an array of arrays containing the found expression and each subexpression. + * @return ($lazy is true ? \Generator<int, array> : array[]) */ public static function matchAll( string $subject, @@ -602,12 +657,10 @@ class Strings $flags = PREG_OFFSET_CAPTURE | ($unmatchedAsNull ? PREG_UNMATCHED_AS_NULL : 0); return (function () use ($utf8, $captureOffset, $flags, $subject, $pattern, $offset) { $counter = 0; - $m = []; while ( $offset <= strlen($subject) - ($counter ? 1 : 0) && self::pcre('preg_match', [$pattern, $subject, &$m, $flags, $offset]) ) { - /** @var list<array{string, int}> $m */ $offset = $m[0][1] + max(1, strlen($m[0][0])); if (!$captureOffset) { $m = array_map(fn($item) => $item[0], $m); @@ -625,9 +678,10 @@ class Strings $flags = is_int($captureOffset) // back compatibility ? $captureOffset - : ($captureOffset ? PREG_OFFSET_CAPTURE : 0) | ($unmatchedAsNull ? PREG_UNMATCHED_AS_NULL : 0) | ($patternOrder ? PREG_PATTERN_ORDER : 0); + : ($captureOffset ? PREG_OFFSET_CAPTURE : 0) + | ($unmatchedAsNull ? PREG_UNMATCHED_AS_NULL : 0) + | ($patternOrder ? PREG_PATTERN_ORDER : 0); - $m = []; self::pcre('preg_match_all', [ $pattern, $subject, &$m, ($flags & PREG_PATTERN_ORDER) ? $flags : ($flags | PREG_SET_ORDER), @@ -640,8 +694,7 @@ class Strings /** - * Replaces all occurrences matching the regular expression $pattern, which can be a string or array in the form `pattern => replacement`. - * @param string|array<string, string> $pattern + * Replaces all occurrences matching regular expression $pattern which can be string or array in the form `pattern => replacement`. */ public static function replace( string $subject, @@ -661,7 +714,7 @@ class Strings $flags = ($captureOffset ? PREG_OFFSET_CAPTURE : 0) | ($unmatchedAsNull ? PREG_UNMATCHED_AS_NULL : 0); if ($utf8) { - $pattern = is_array($pattern) ? array_map(fn($item) => $item . 'u', $pattern) : $pattern . 'u'; + $pattern .= 'u'; if ($captureOffset) { $replacement = fn($m) => $replacement(self::bytesToChars($subject, [$m])[0]); } @@ -682,10 +735,6 @@ class Strings } - /** - * @param list<array<array{string, int}>> $groups - * @return list<array<array{string, int}>> - */ private static function bytesToChars(string $s, array $groups): array { $lastBytes = $lastChars = 0; @@ -706,12 +755,8 @@ class Strings } - /** - * @param callable-string $func - * @param list<mixed> $args - * @internal - */ - public static function pcre(string $func, array $args): mixed + /** @internal */ + public static function pcre(string $func, array $args) { $res = Callback::invokeSafe($func, $args, function (string $message) use ($args): void { // compile-time error, not detectable by preg_last_error @@ -719,7 +764,7 @@ class Strings }); if (($code = preg_last_error()) // run-time error, but preg_last_error & return code are liars - && ($res === null || !in_array($func, ['preg_filter', 'preg_replace_callback', 'preg_replace'], strict: true)) + && ($res === null || !in_array($func, ['preg_filter', 'preg_replace_callback', 'preg_replace'], true)) ) { throw new RegexpException(preg_last_error_msg() . ' (pattern: ' . implode(' or ', (array) $args[0]) . ')', $code); diff --git a/vendor/nette/utils/src/Utils/Type.php b/vendor/nette/utils/src/Utils/Type.php index 329475c..ae1451c 100644 --- a/vendor/nette/utils/src/Utils/Type.php +++ b/vendor/nette/utils/src/Utils/Type.php @@ -8,17 +8,18 @@ namespace Nette\Utils; use Nette; -use function array_map, array_search, array_splice, array_values, count, explode, implode, is_a, is_resource, is_string, strcasecmp, strtolower, substr, trim; +use function count, is_resource, is_string; +use const PHP_VERSION_ID; /** * PHP type reflection. */ -final readonly class Type +final class Type { - /** @var list<string|self> */ + /** @var array<int, string|self> */ private array $types; - private ?string $singleName; + private bool $simple; private string $kind; // | & @@ -31,19 +32,16 @@ final readonly class Type ): ?self { $type = $reflection instanceof \ReflectionFunctionAbstract - ? $reflection->getReturnType() ?? ($reflection instanceof \ReflectionMethod ? $reflection->getTentativeReturnType() : null) + ? $reflection->getReturnType() ?? (PHP_VERSION_ID >= 80100 && $reflection instanceof \ReflectionMethod + ? $reflection->getTentativeReturnType() + : null) : $reflection->getType(); return $type ? self::fromReflectionType($type, $reflection, asObject: true) : null; } - /** @return ($asObject is true ? self : self|string) */ - private static function fromReflectionType( - \ReflectionType $type, - \ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionProperty $of, - bool $asObject, - ): self|string + private static function fromReflectionType(\ReflectionType $type, $of, bool $asObject): self|string { if ($type instanceof \ReflectionNamedType) { $name = self::resolve($type->getName(), $of); @@ -110,40 +108,34 @@ final readonly class Type */ public static function resolve( string $type, - \ReflectionFunction|\ReflectionMethod|\ReflectionParameter|\ReflectionProperty $of, + \ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionProperty $of, ): string { $lower = strtolower($type); if ($of instanceof \ReflectionFunction) { return $type; - } - - $class = $of->getDeclaringClass(); - if ($class === null) { - return $type; } elseif ($lower === 'self') { - return $class->name; + return $of->getDeclaringClass()->name; } elseif ($lower === 'static') { - return ($of instanceof ReflectionMethod ? $of->getOriginalClass() : $class)->name; - } elseif ($lower === 'parent' && $class->getParentClass()) { - return $class->getParentClass()->name; + return ($of instanceof ReflectionMethod ? $of->getOriginalClass() : $of->getDeclaringClass())->name; + } elseif ($lower === 'parent' && $of->getDeclaringClass()->getParentClass()) { + return $of->getDeclaringClass()->getParentClass()->name; } else { return $type; } } - /** @param array<string|self> $types */ private function __construct(array $types, string $kind = '|') { $o = array_search('null', $types, strict: true); if ($o !== false) { // null as last - array_splice($types, (int) $o, 1); + array_splice($types, $o, 1); $types[] = 'null'; } - $this->types = array_values($types); - $this->singleName = is_string($types[0]) && ($types[1] ?? 'null') === 'null' ? $types[0] : null; + $this->types = $types; + $this->simple = is_string($types[0]) && ($types[1] ?? 'null') === 'null'; $this->kind = count($types) > 1 ? $kind : ''; } @@ -151,8 +143,8 @@ final readonly class Type public function __toString(): string { $multi = count($this->types) > 1; - if ($this->singleName !== null) { - return ($multi ? '?' : '') . $this->singleName; + if ($this->simple) { + return ($multi ? '?' : '') . $this->types[0]; } $res = []; @@ -164,7 +156,7 @@ final readonly class Type /** - * Returns a union type that accepts both the current type and the given type. + * Returns a type that accepts both the current type and the given type. */ public function with(string|self $type): self { @@ -175,14 +167,14 @@ final readonly class Type default => new self(array_unique( array_merge($this->isIntersection() ? [$this] : $this->types, $type->isIntersection() ? [$type] : $type->types), SORT_REGULAR, - ), '|'), + )), }; } /** * Returns the array of subtypes that make up the compound type as strings. - * @return list<string|array<string|array<mixed>>> + * @return array<int, string|string[]> */ public function getNames(): array { @@ -191,8 +183,8 @@ final readonly class Type /** - * Returns the array of subtypes that make up the compound type as Type objects. - * @return list<self> + * Returns the array of subtypes that make up the compound type as Type objects: + * @return self[] */ public function getTypes(): array { @@ -205,7 +197,9 @@ final readonly class Type */ public function getSingleName(): ?string { - return $this->singleName; + return $this->simple + ? $this->types[0] + : null; } @@ -228,36 +222,36 @@ final readonly class Type /** - * Checks whether it is a simple (non-compound) type. Single nullable types such as ?int are also considered simple. + * Returns true whether it is a simple type. Single nullable types are also considered to be simple types. */ public function isSimple(): bool { - return $this->singleName !== null; + return $this->simple; } - #[\Deprecated('use isSimple()')] + /** @deprecated use isSimple() */ public function isSingle(): bool { - return $this->singleName !== null; + return $this->simple; } /** - * Checks whether it is a simple PHP built-in type (int, string, bool, etc.). + * Returns true whether the type is both a simple and a PHP built-in type. */ public function isBuiltin(): bool { - return $this->singleName !== null && Validators::isBuiltinType($this->singleName); + return $this->simple && Validators::isBuiltinType($this->types[0]); } /** - * Checks whether it is a simple class or interface name (not a built-in type). + * Returns true whether the type is both a simple and a class name. */ public function isClass(): bool { - return $this->singleName !== null && !Validators::isBuiltinType($this->singleName); + return $this->simple && !Validators::isBuiltinType($this->types[0]); } @@ -266,12 +260,12 @@ final readonly class Type */ public function isClassKeyword(): bool { - return $this->singleName !== null && Validators::isClassKeyword($this->singleName); + return $this->simple && Validators::isClassKeyword($this->types[0]); } /** - * Checks whether a value of the given type could be assigned to this type. + * Verifies type compatibility. For example, it checks if a value of a certain type could be passed as a parameter. */ public function allows(string|self $type): bool { @@ -286,7 +280,6 @@ final readonly class Type } - /** @param array<string> $givenTypes */ private function allowsAny(array $givenTypes): bool { return $this->isUnion() @@ -295,17 +288,13 @@ final readonly class Type } - /** - * @param array<string> $ourTypes - * @param array<string> $givenTypes - */ private function allowsAll(array $ourTypes, array $givenTypes): bool { return Arrays::every( $ourTypes, - fn(string $ourType) => Arrays::some( + fn($ourType) => Arrays::some( $givenTypes, - fn(string $givenType) => Validators::isBuiltinType($ourType) + fn($givenType) => Validators::isBuiltinType($ourType) ? strcasecmp($ourType, $givenType) === 0 : is_a($givenType, $ourType, allow_string: true), ), diff --git a/vendor/nette/utils/src/Utils/Validators.php b/vendor/nette/utils/src/Utils/Validators.php index b11d7e1..ff998e7 100644 --- a/vendor/nette/utils/src/Utils/Validators.php +++ b/vendor/nette/utils/src/Utils/Validators.php @@ -8,7 +8,7 @@ namespace Nette\Utils; use Nette; -use function array_key_exists, class_exists, explode, gettype, interface_exists, is_callable, is_float, is_int, is_iterable, is_numeric, is_object, is_string, preg_match, str_ends_with, str_replace, str_starts_with, strlen, strtolower, substr, trait_exists, var_export; +use function array_key_exists, gettype, is_float, is_int, is_object, is_string, strlen; /** @@ -24,7 +24,7 @@ class Validators 'never' => 1, 'true' => 1, ]; - /** @var array<string, ?(callable(mixed): bool)> */ + /** @var array<string,?callable> */ protected static $validators = [ // PHP types 'array' => 'is_array', @@ -74,7 +74,7 @@ class Validators 'type' => [self::class, 'isType'], ]; - /** @var array<string, callable(mixed): int> */ + /** @var array<string,callable> */ protected static $counters = [ 'string' => 'strlen', 'unicode' => [Strings::class, 'length'], @@ -112,22 +112,22 @@ class Validators /** - * Verifies that item $key in array exists and is of expected types separated by pipe. + * Verifies that element $key in array is of expected types separated by pipe. * @param mixed[] $array * @throws AssertionException */ public static function assertField( array $array, - int|string $key, + $key, ?string $expected = null, string $label = "item '%' in array", ): void { if (!array_key_exists($key, $array)) { - throw new AssertionException('Missing ' . str_replace('%', (string) $key, $label) . '.'); + throw new AssertionException('Missing ' . str_replace('%', $key, $label) . '.'); } elseif ($expected) { - static::assert($array[$key], $expected, str_replace('%', (string) $key, $label)); + static::assert($array[$key], $expected, str_replace('%', $key, $label)); } } @@ -144,6 +144,7 @@ class Validators } continue; + } elseif (str_starts_with($item, '?')) { $item = substr($item, 1); if ($value === null) { @@ -166,6 +167,7 @@ class Validators } continue; + } elseif (!$value instanceof $type) { continue; } @@ -195,7 +197,7 @@ class Validators /** * Finds whether all values are of expected types separated by pipe. - * @param iterable<mixed> $values + * @param mixed[] $values */ public static function everyIs(iterable $values, string $expected): bool { @@ -259,7 +261,7 @@ class Validators /** * Checks if the value is 0, '', false or null. - * @return ($value is 0|0.0|''|false|null ? true : false) + * @return ($value is 0|''|false|null ? true : false) */ public static function isNone(mixed $value): bool { @@ -288,7 +290,6 @@ class Validators /** * Checks if the value is in the given range [min, max], where the upper or lower limit can be omitted (null). * Numbers, strings and DateTime objects can be compared. - * @param array{int|float|string|\DateTimeInterface|null, int|float|string|\DateTimeInterface|null} $range */ public static function isInRange(mixed $value, array $range): bool { @@ -337,15 +338,14 @@ class Validators public static function isUrl(string $value): bool { $alpha = "a-z\x80-\xFF"; - $octet = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])'; // 0..255 return (bool) preg_match(<<<XX (^(?n) https?://( (([-_0-9$alpha]+\\.)* # subdomain [0-9$alpha]([-0-9$alpha]{0,61}[0-9$alpha])?\\.)? # domain [$alpha]([-0-9$alpha]{0,17}[$alpha])? # top domain - |$octet(\\.$octet){3} # IPv4 - |\\[[0-9a-f:]{3,39}] # IPv6 + |\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3} # IPv4 + |\\[[0-9a-f:]{3,39}\\] # IPv6 )(:\\d{1,5})? # port (/\\S*)? # path (\\?\\S*)? # query @@ -360,7 +360,7 @@ class Validators */ public static function isUri(string $value): bool { - return (bool) preg_match('#^[a-z\d+.-]+:\S+$#Di', $value); + return (bool) preg_match('#^[a-z\d+\.-]+:\S+$#Di', $value); } diff --git a/vendor/nette/utils/src/Utils/exceptions.php b/vendor/nette/utils/src/Utils/exceptions.php index ba1cdfe..8a7f981 100644 --- a/vendor/nette/utils/src/Utils/exceptions.php +++ b/vendor/nette/utils/src/Utils/exceptions.php @@ -46,19 +46,3 @@ class RegexpException extends \Exception class AssertionException extends \Exception { } - - -/** - * The process failed to run successfully. - */ -class ProcessFailedException extends \RuntimeException -{ -} - - -/** - * The process execution exceeded its timeout limit. - */ -class ProcessTimeoutException extends \RuntimeException -{ -} diff --git a/vendor/symfony/deprecation-contracts/.gitignore b/vendor/symfony/deprecation-contracts/.gitignore new file mode 100644 index 0000000..c49a5d8 --- /dev/null +++ b/vendor/symfony/deprecation-contracts/.gitignore @@ -0,0 +1,3 @@ +vendor/ +composer.lock +phpunit.xml diff --git a/vendor/symfony/deprecation-contracts/LICENSE b/vendor/symfony/deprecation-contracts/LICENSE index 0ed3a24..406242f 100644 --- a/vendor/symfony/deprecation-contracts/LICENSE +++ b/vendor/symfony/deprecation-contracts/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2020-present Fabien Potencier +Copyright (c) 2020-2022 Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/symfony/deprecation-contracts/README.md b/vendor/symfony/deprecation-contracts/README.md index 9814864..4957933 100644 --- a/vendor/symfony/deprecation-contracts/README.md +++ b/vendor/symfony/deprecation-contracts/README.md @@ -22,5 +22,5 @@ trigger_deprecation('symfony/blockchain', '8.9', 'Using "%s" is deprecated, use This will generate the following message: `Since symfony/blockchain 8.9: Using "bitcoin" is deprecated, use "fabcoin" instead.` -While not recommended, the deprecation notices can be completely ignored by declaring an empty +While not necessarily recommended, the deprecation notices can be completely ignored by declaring an empty `function trigger_deprecation() {}` in your application. diff --git a/vendor/symfony/deprecation-contracts/composer.json b/vendor/symfony/deprecation-contracts/composer.json index 9279eb1..1c1b4ba 100644 --- a/vendor/symfony/deprecation-contracts/composer.json +++ b/vendor/symfony/deprecation-contracts/composer.json @@ -15,7 +15,7 @@ } ], "require": { - "php": ">=8.1" + "php": ">=8.0.2" }, "autoload": { "files": [ @@ -25,7 +25,7 @@ "minimum-stability": "dev", "extra": { "branch-alias": { - "dev-main": "3.7-dev" + "dev-main": "3.0-dev" }, "thanks": { "name": "symfony/contracts", diff --git a/vendor/symfony/polyfill-php80/PhpToken.php b/vendor/symfony/polyfill-php80/PhpToken.php index cd78c4c..0f6b65e 100644 --- a/vendor/symfony/polyfill-php80/PhpToken.php +++ b/vendor/symfony/polyfill-php80/PhpToken.php @@ -51,11 +51,11 @@ class PhpToken implements \Stringable public function getTokenName(): ?string { - if ('UNKNOWN' === $name = token_name($this->id)) { - $name = \strlen($this->text) > 1 || \ord($this->text) < 32 ? null : $this->text; + if ($this->id < 256) { + return \chr($this->id & 0xFF); } - return $name; + return 'UNKNOWN' === ($name = token_name($this->id)) ? null : $name; } /** @@ -92,13 +92,15 @@ class PhpToken implements \Stringable $tokens = token_get_all($code, $flags); foreach ($tokens as $index => $token) { if (\is_string($token)) { - $id = \ord($token); + // b" is the only such token longer than one char + $id = \ord($token[-1]); $text = $token; } else { [$id, $text, $line] = $token; } $tokens[$index] = new static($id, $text, $line, $position); $position += \strlen($text); + $line += preg_match_all('/\r\n?|\n/', $text); } return $tokens;